Swap Nodes in Pairs leetcode java


題目:

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.http://i.cnblogs.com/EditPosts.aspx?opt=1

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

 

題解:

這道題考察了基本的鏈表操作,注意當改變指針連接時,要用一個臨時指針指向原來的next值,否則鏈表丟鏈,無法找到下一個值。

本題的解題方法是:

需要運用fakehead來指向原指針頭,防止丟鏈,用兩個指針,ptr1始終指向需要交換的pair的前面一個node,ptr2始終指向需要交換的pair的第一個node。

 然后就是進行鏈表交換。

需要用一個臨時指針nextstart, 指向下一個需要交換的pair的第一個node,保證下一次交換的正確進行。

然后就進行正常的鏈表交換,和指針挪動就好。

 當鏈表長度為奇數時,ptr2.next可能為null;

 當鏈表長度為偶數時,ptr2可能為null。

所以把這兩個情況作為終止條件,在while判斷就好,最后返回fakehead.next。

代碼如下:

 1    public ListNode swapPairs(ListNode head) {
 2        if(head ==  null || head.next ==  null)
 3          return head;
 4     
 5       ListNode fakehead =  new ListNode(-1);
 6       fakehead.next = head;
 7       
 8       ListNode ptr1 = fakehead;
 9       ListNode ptr2 = head;
10       
11        while(ptr2!= null && ptr2.next!= null){
12           ListNode nextstart = ptr2.next.next;
13           ptr2.next.next = ptr2;
14           ptr1.next = ptr2.next;
15           ptr2.next = nextstart;
16           ptr1 = ptr2;
17           ptr2 = ptr2.next;
18       }
19      return fakehead.next;
20   }

 Reference://http://gongxuns.blogspot.com/2012/12/leetcodeswap-nodes-in-pairs.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM