题目
- 遍历整个链表, 获得一个有序数组.
- 将该数组转为一个包含两个链表元素的数组的二维数组.(
[[ListNode, ListNode], [ListNode, ListNode]...]
)
- 对每个数组进行反转.
- 将二维数组转为有序数组, 同时遍历数组, 改变
next
.
- 返回数组第一个元素即可.
/**
* 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]
};