LeetCode 24 Swap Nodes in Pairs

chi633發表於2017-12-21

題目

給一個連結串列,兩兩交換其中的節點,然後返回交換後的連結串列。

樣例 給出 1->2->3->4, 你應該返回的連結串列是 2->1->4->3。

分析

由於沒有頭結點不好操作 那就自己加一個頭結點

程式碼

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @return a ListNode
     */
    public ListNode swapPairs(ListNode head) {
        // Write your code here
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        head = dummy;
        while (head.next != null && head.next.next != null) {
            ListNode n1 = head.next, n2 = head.next.next;
            // head->n1->n2->...
            // => head->n2->n1->...
            head.next = n2;
            n1.next = n2.next;
            n2.next = n1;
            
            // move to next pair
            head = n1;
        }
        
        return dummy.next;
    }
}
複製程式碼

相關文章