[LeetCode]Swap Nodes in Pairs

上面是lc的单链表题目,下面我又自己加了个双向链表的情况

 

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        ListNode pre = head;
        ListNode p1 = head.next;
        ListNode p2 = head.next.next;
        ListNode p3 = head.next.next.next;
        while (p1 != null && p2 != null) {
            p1.next = p3;
            p2.next = p1;
            pre.next = p2;
            pre = p1;
            p1 = p3;
            if (p1 == null) {
                break;
            }
            p2 = p1.next;
            if (p2 == null) {
                break;
            }
            p3 = p2.next;
        }
        return head.next;
    }
}

 

 

 

public class Solution {
    public duListNode solution (duListNode head, duListNode end) {
        if (head == null || head.next == null) {
            return head;
        }
        duListNode dummy = new duListNode(0);
        dummy.next = head;
        head = dummy;
        dummy = new duListNode(0);
        end.next = dummy;
        dummy.pre = end;
        end =  end.next;
        duListNode p1 = head;
        duListNode p2 = head.next;
        duListNode p3 = head.next.next;
        duListNode p4 = head.next.next.next;
        while (p2 != null && p3 != null) {
            p2.next = p4;
            p4.pre = p2;
            p1.next = p3;
            p3.pre = p1;
            p3.next = p2;
            p2.pre = p3;
            if (p4 == end || p4.next == end) {
                break;
            }
            p1 = p2;
            p2 = p4;
            p3 = p4.next;
            p4 = p3.next;
        }
        end = end.pre;
        end.next = null;
        return head.next;
        
    }
}



public class duListNode {
    int val;
    duListNode next;
    duListNode pre;
    duListNode (int val) {
        this.val = val;
    }
}

 

posted @ 2015-12-05 03:54  Weizheng_Love_Coding  阅读(156)  评论(0)    收藏  举报