对链表的相邻节点两两交换
var swapPairs = function(head) {
var dummy = new ListNode;
dummy.next = head;
var prev = dummy
while(head && head.next){
var arr = swap(prev, head, head.next, head.next.next)
prev = arr[0]
head = arr[1]
}
return dummy.next
};
function swap(a, b, c, d){
a.next = c
c.next = b;
b.next = d;
return [b, d]
//a c b d
//dummy
}
数组方法构建
var swapPairs = function(node) {
var nodes = [], dummy = new ListNode, prev = dummy
var map = {}, index = 0
while(node){
if(node.next){
nodes.push(node.next, node)
node = node.next.next //连续跳两步
}else{
nodes.push(node)
break
}
}
for(var i = 0, el = null; i < nodes.length; i++){
el = nodes[i];
prev = prev.next = el
}
Object(el).next = null
return dummy.next
};