Skip to content

Latest commit

 

History

History
51 lines (47 loc) · 1.19 KB

24.swap-nodes-in-pairs.md

File metadata and controls

51 lines (47 loc) · 1.19 KB

两两交换链表中的节点

题目

思路

  1. 遍历整个链表, 获得一个有序数组.
  2. 将该数组转为一个包含两个链表元素的数组的二维数组.([[ListNode, ListNode], [ListNode, ListNode]...])
  3. 对每个数组进行反转.
  4. 将二维数组转为有序数组, 同时遍历数组, 改变next.
  5. 返回数组第一个元素即可.
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var swapPairs = function(head) {
  if (!head || !head.next) {
    return head
  }
  const arr = []
  while (head) {
    arr.push(head)
    head = head.next
  }
  const arr2D = arr.reduce((prev, curr) => {
    const { length } = prev
    if (length > 0 && prev[length - 1].length === 1) {
      prev[length - 1].unshift(curr)
    } else {
      prev.push([curr])
    }
    return prev
  }, [])
  const results = arr2D.reduce((prev, curr) => {
    return prev.concat(curr)
  }, [])
  for (let i = 0; i < results.length; i++) {
    results[i].next = results[i + 1]
  }
  return results[0]
};