LeetCode 24.Swap Nodes in Pairs 成對交換鏈表節點

24.成對交換鏈表節點

24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:

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

本題的解題思路很簡單。我們首先提取爲list添加一個頭結點。然後我設置三個指針,pre,cur,post。cur和post是需要兩兩交換的指針。令pre.next = post,然後post.next = cur。這樣子就達到了交換的目的,交換後繼續更新三個指針的位置。直到最後面得出結果。

/**
 * 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 || null == head.next){
            return head;
        }
        ListNode first = new ListNode(0);
        first.next = head;
        ListNode pre = first;
        ListNode cur = head;
        ListNode post = cur.next;
        while(cur != null && post != cur){
            ListNode newNode = post.next;
            pre.next = post;
            post.next = cur;
            
            cur.next = newNode;
            pre = cur;
            cur = pre.next;
            if(cur == null){
                return first.next;
            } else if(cur.next != null){
                post = cur.next;
            } else {
                post = cur;
            }
        }
        return first.next;   
    }
}
遞歸

使用遞歸進行操作相對於迭代而言會比較抽象一點,但是也不是很難理解。其核心思想是和迭代的一樣的。每次兩對兩對的更新。只不過遞歸是從後往前交換,而迭代時從前往後交換。

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode nextnextSwapped = swapPairs(head.next.next);
        ListNode newHead = head.next;
        newHead.next = head;
        head.next = nextnextSwapped;
        return newHead;    
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章