24. Swap Nodes in Pairs
24. 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.
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 14 //如果全部交换还简单点,但是这里要求只是相邻的旋转。 15 16 17 //假设只有1个节点,那直接返回。因为后面的一个是null。 18 //假设有2个节点,那只要把second的next指向first即可,然后返回last 19 //假设有3个节点,前2个节点如第二步一样,剩下1个节点和第一步一样。 20 //假设有4个节点,递归走第二步 21 if(head === null || head.next === null){ 22 return head; 23 } 24 25 var first = head; 26 var last = head.next; 27 28 first.next = swapPairs(last.next); 29 last.next = first; 30 31 32 return last; 33 34 };