将给定的链表中每两个相邻的节点交换一次,返回链表的头指针
例如,
给出1->2->3->4,你应该返回链表2->1->4->3。
你给出的算法只能使用常量级的空间。你不能修改列表中的值,只能修改节点本身。
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return ListNode类
*/
function swapPairs( head ) {
// write code here
if(head==null || head.next == null){ return head }
var top = {}
top.next = head
var current = top
while(current.next.next){
var node1 = current.next
var node2 = current.next.next
current.next = node2
node1.next = node2.next
node2.next = node1
current = current.next.next
if(current.next == null){
return top.next
}
}
return top.next
}
module.exports = {
swapPairs : swapPairs
};
京公网安备 11010502036488号