본문 바로가기
매일 해내는 개발/Develog

[Develog] 링크드리스트로 투두리스트 구현하기.js

by 해야지 2023. 3. 21.
반응형

며칠 전에 진산님께서 모의면접시 `투두리스트 구현을 배열로 할래요 링크드리스트로할래요?`라는 질문을 받았다고 해서 생각해봤다.
그 동안은 배열로 구현하는게 편하니까 배열로만 구현했었다.
저 질문의 의도는 삽입,삭제가 유리한 링크드리스트를 쓸거냐 자료에 접근이 빠른 배열을 쓸거냐인데
투두리스트는 일단 데이터를 삽입하고 삽입한 데이터를 순서에 상관없이 접근해서 상태를 변경시켜줘야한다. 삭제를 할 때도 있지만 보통은 내가 뭘했는지 확인하기 위해 삭제를 잘 하지 않는다(나의 경우)
그래서 삽입과 자료 접근의 비율이 거의 1:1이라고 생각해서 어느 것을 써도 상관이 없을 것 같지만
완료될 때마 삭제하는 유저가 있을 수도 있으니 그런 상황을 생각하면 삽입,삭제 : 자료 접근 = 2:1의 비율이 된다.
이런 상황에서는 링크드리스트가 유리하다.
그래서 링크드리스트로 구현한 코드이다.

//링크드리스트 구현
function createNode(value, nextNode = null) {
  return { value, nextNode };
}

function addNode(head, value) {
  const newNode = createNode(value);
  if (!head) {
    return newNode;
  }
  let currentNode = head;
  while (currentNode.nextNode) {
    currentNode = currentNode.nextNode;
  }
  currentNode.nextNode = newNode;
  return head;
}

function deleteNode(head, value) {
  if (head && head.value === value) {
    return head.nextNode;
  }
  let currentNode = head;
  while (currentNode && currentNode.nextNode) {
    if (currentNode.nextNode.value === value) {
      currentNode.nextNode = currentNode.nextNode.nextNode;
      return head;
    }
    currentNode = currentNode.nextNode;
  }
  return head;
}

function printList(head) {
  let currentNode = head;
  while (currentNode) {
    console.log(currentNode.value);
    currentNode = currentNode.nextNode;
  }
}

이를 활용한 투두리스트 구현

//투두리스트
let todoList = null;

function addTodo(todo) {
  todoList = addNode(todoList, todo);
}

function deleteTodo(todo) {
  todoList = deleteNode(todoList, todo);
}

function printTodos() {
  printList(todoList);
}

 

반응형

댓글