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

LeetCode 24 Swap Nodes in Pairs

next 頭結點 code pair turn || lis AS urn

public class SwapNodesInPairs {

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode(int x) { val = x; }
     * }
     */
    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        ;
    }


    class Solution {

        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            //當前節點
            ListNode p = head;
            //next節點
            ListNode q = head.next;
            //before節點
            ListNode r = null;
            head = q;
            while (p != null && q != null) {
                p.next = q.next;
                q.next = p;
                if (r != null) {
                    r.next = q;
                }
                //更新
                r = p;
                p = p.next;

                if (p != null) {
                    q = p.next;
                }
            }
            return head;
        }
    }
}

遞歸版本

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null){
            return null;
        }
        if(head.next == null){
            return head;
        }
        ListNode next = head.next;
        //交換後的頭結點的下一個節點是 下一對節點的尾節點
        head.next = swapPairs(next.next);
        next.next = head;
        return next;
    }
    
}

LeetCode 24 Swap Nodes in Pairs