[LintCode] Swap Nodes in Pairs

411 查看

Problem

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

Example

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

Note

指针为p,我们选择swap的两个结点是p.nextp.next.next。要注意while循环的边界条件,这两个结点不能为空。主要思路是先用nexttemp两个新结点去保存p.next.next.nextp.next两个结点。完成交换之后,连接tempnext,并让p前进至此时的temp结点。

Solution

    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if (head == null) return head;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode p = dummy;
            while (p.next != null && p.next.next != null) {
                ListNode next = p.next.next.next;
                ListNode temp = p.next;
                p.next = p.next.next;
                p.next.next = temp;
                temp.next = next;
                p = temp;
            }
            return dummy.next;
        }
    }

OR

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;        
        ListNode cur = dummy;
        while (cur.next != null && cur.next.next != null) {
            ListNode n1 = cur.next;
            ListNode n2 = cur.next.next;
            cur.next = n2;
            n1.next = n2.next;
            n2.next = n1;
            cur = n1;
        }
        return dummy.next;
    }
}