Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
交换链表中相邻的两个节点,要求O(1)的空间复杂度。
1 /** 2 * Definition for singly-linked list. 3 * function ListNode(val) { 4 * this.val = val; 5 * this.next = null; 6 * } 7 */ 8 /** 9 * @param {ListNode} head 10 * @return {ListNode} 11 */ 12 var swapPairs = function(head) { 13 var newHead = new ListNode(-1), start = newHead; 14 newHead.next = head; 15 while(start.next !== null && start.next.next !== null) 16 start = reverse(start, start.next, start.next.next); 17 return newHead.next; 18 19 function reverse(h, node1, node2){ 20 var tail = node2.next; 21 h.next = node2; 22 node2.next = node1; 23 node1.next = tail; 24 return node1; 25 } 26 };