1. 程式人生 > >24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

ext this next air last lis list node 如果

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 };

24. Swap Nodes in Pairs