143. Reorder List

2021-10-04  本文已影响0人  jluemmmm

重排链表
L0 → L1 → … → Ln - 1 → Ln
重写为
L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

寻找链表中点 + 链表逆序 + 合并链表

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function(head) {
  if (!head) return;
  let slow = head;
  let fast = head;
  while (fast && fast.next){
    slow = slow.next;
    fast = fast.next.next;
  }
  
  let prev = null;
  let cur = slow;
  while (cur) {
    let tmp = cur.next;
    cur.next = prev;
    prev = cur;
    cur = tmp;
  }
  
  let first = head;
  let second = prev;
  while (second.next) {
    let tmp = first.next;
    first.next = second;
    first = tmp;
    
    tmp = second.next;
    second.next = first;
    second = tmp
  }
};



上一篇 下一篇

猜你喜欢

热点阅读