算法笔记5:重排链表

142 阅读1分钟

143.重排链表

这道题目感觉是一道对链表操作的整合题目了,主要用到:

  1. 快慢指针找中点
  2. 链表反转
  3. 链表合并

代码如下:

// merge linklists
const mergeLists = (p, q) => {
  let i = p;
  let j = q;
  let flag = false;
  while(i.next && j.next) {
    if (!flag) {
      const t = i.next;
      i.next = j;
      i = t;
      flag = true
    } else {
      const t = j.next;
      j.next = i;
      j = t;
      flag = false;
    }
  }
  return p;
}

// reverse linklist
const reverseList = head => {
  if (!head || !head.next) {
    return head;
  }
  
  const last = reverseList(head.next);
  head.next.next = head;
  head.next = null;
  return last;
}

const reorderList = head => {
  // edge cases
  // len 1
  let p = head.next;
  if (!p) return head;
  // len 2
  let q = head.next.next;
  if (!q) return head;

  while (q.next) {
    p = p.next;
    q = q.next.next;
  }
  
  q = reverseList(p);
  return mergeLists(head, q);
}

比起都放到数组里面然后按顺序连接节省了空间复杂度:O(N) -> O(1)