[JavaScript] Circular-linked list

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

Task

--- Directions
Given a linked list, return true if the list
is circular, false if it is not.
--- Examples
const l = new List();
const a = new Node('a');
const b = new Node('b');
const c = new Node('c');
l.head = a;
a.next = b;
b.next = c;
c.next = b;
circular(l) // true

Solution

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

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

    if (slow === fast) {
      return true;
    }
  }
  return false;
}
profile
그림도 그리는 개발자 🎨👩‍💻

0개의 댓글