Leetcode24--->Swap Nodes in Pairs(交換單鏈表中相鄰的兩個節點)


題目:給定一個單鏈表,交換兩個相鄰的節點,且返回交換之后的頭節點

舉例:

Given 1->2->3->4, you should return the list as 2->1->4->3.

解題思路:

題目本身很簡單,但是要注意一些細節:

1.  兩對節點之間的連接

2.  如果只剩下一個節點,則不需要交換

代碼如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode swapPairs(ListNode head) {
11         if(head == null)
12             return head;
13         ListNode cur = head;
14         ListNode prev = cur;  // 連接每對節點
15         if(cur.next != null)
16             head = cur.next;
17         while(cur != null && cur.next != null){
18             prev.next = cur.next;
19             ListNode next = cur.next.next;  // next用來保存下一對節點的開始節點
20             cur.next.next = cur;
21             cur.next = next;  
22             prev = cur;  // prev指向每一對反轉之后節點的第二個節點
23             cur = next;  // cur指向每一對節點的第一個節點
24         }
25         return head;
26     }
27 }

 


免責聲明!

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



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