[LintCode] Swap Nodes in Pairs

发布时间:2019-06-29 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LintCode] Swap Nodes in Pairs脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LintCode] Swap Nodes in Pairs全部内容,希望文章能够帮你解决[LintCode] Swap Nodes in Pairs所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。