1. 程式人生 > >【LeetCode】 24 兩兩交換連結串列中的節點

【LeetCode】 24 兩兩交換連結串列中的節點

在這裡插入圖片描述


解題思路:
1 重點:如何在交換完了之後,獲得進行交換動作的兩個節點的前驅節點;思路和反轉連結串列類似,維護一個前驅節點即可。

程式碼:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        
        if (head == null)
            return null;
        
        ListNode prepre = new ListNode(-1);
        prepre.next = head;
        
        ListNode pre = head;
        ListNode now = head.next;
        
        ListNode result = prepre;
        
        for (;now != null;){
        
            pre.next = now.next;
            now.next = pre;
            prepre.next = now;
        
            if (pre.next == null)
                break;
            
            prepre = pre;
            pre = pre.next;
            now = pre.next;
        }
        
        return result.next;
    }
}