[JavaScript] midpoint-linked list

bbio3o·2021년 2월 1일
0
post-thumbnail

Task

--- Directions
Return the 'middle' node of a linked list.
If the list has an even number of elements, return
the node at the end of the first half of the list.
Do not use a counter variable, do not retrieve
the size of the list, and only iterate
through the list one time.
--- Example
const l = new LinkedList();
l.insertLast('a')
l.insertLast('b')
l.insertLast('c')
midpoint(l); // returns { data: 'b' }

Solution

function midpoint(list) {
  let slow = list.getFirst();
  let fast = list.getFirst();

  while (fast.next && fast.next.next) {
    slow = slow.next;
    fast = fast.next.next;
  }

  return slow;
}

문제풀이

list.getFirst() 대신 list.head()도 가능하다.

profile
그림도 그리는 개발자 🎨👩‍💻

0개의 댓글