码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Swap Nodes in Pairs

时间:2015-12-05 07:12:25      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

上面是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;
    }
}

 

[LeetCode]Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/vision-love-programming/p/5020938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!