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

24.Swap Nodes in Pairs

info res public int ret lap ppa one 代碼

題目鏈接

題目大意:交換單鏈表中的相鄰結點。例子如下:

技術分享圖片

法一:交換兩個相鄰的值,不交換相鄰結點。代碼如下(耗時3ms):

技術分享圖片
 1     public ListNode swapPairs(ListNode head) {
 2         ListNode cur = head;
 3         while(cur != null && cur.next != null) {
 4             int tmp = cur.val;
 5             cur.val = cur.next.val;
 6             cur.next.val = tmp;
7 cur = cur.next.next; 8 } 9 return head; 10 }
View Code

法二:交換結點,叠代。真的很容易弄暈。代碼如下(耗時2ms):

技術分享圖片
 1     public ListNode swapPairs(ListNode head) {
 2         ListNode res = new ListNode(0);
 3         res.next = head;
 4         ListNode cur = res;
 5         while(cur.next != null
&& cur.next.next != null) { 6 //相鄰的第一個節點 7 ListNode pre = cur.next; 8 //相鄰的第二個節點 9 ListNode post = cur.next.next; 10 //開始交換 11 //將第一個節點的next指向第二個節點的next 12 pre.next = post.next; 13 //加入到結果鏈表,結果鏈表的next指向第二個節點,結果鏈表的next的next指向第一個節點
14 cur.next = post; 15 cur.next.next = pre; 16 //回到遍歷 17 cur = cur.next.next; 18 } 19 return res.next; 20 }
View Code

24.Swap Nodes in Pairs