알고리즘 기초 - 5 (linkedList)

Hansoo Kim·2020년 4월 24일
0
  1. midpoint

    // --- Example
    //   const l = new LinkedList();
    //   l.insertLast('a')
    //   l.insertLast('b')
    //   l.insertLast('c')
    //   midpoint(l); // returns { data: 'b' }
    
    function midpoint(list) {
      if (!list) {
        return null;
      }
      let slow = list.head;
      let fast = list.head;
      while (fast.next && fast.next.next) {
        slow = slow.next;
        fast = fast.next.next;
      }
      return slow;
    }
  2. circular

    // --- 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
    
    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;
    }
  3. from last

    // --- Examples
    //    const list = new List();
    //    list.insertLast('a');
    //    list.insertLast('b');
    //    list.insertLast('c');
    //    list.insertLast('d');
    //    fromLast(list, 2).data // 'b'
    
    function fromLast(list, n) {
      let slow = list.getFirst();
      let fast = list.getFirst();
      while (n > 0) {
        fast = fast.next;
        n--;
      }
      while (fast.next) {
        slow = slow.next;
        fast = fast.next;
      }
      return slow;
    }

0개의 댓글