您的位置:首页 > Web前端 > Node.js

24. Swap Nodes in Pairs | Java最短代码实现

2016-04-09 09:48 609 查看
原题链接:24. Swap Nodes in Pairs
【思路】

本题考查节点的基本操作。每轮循环,如果存在2个节点,则交换前后位置,用p、q两个指针来完成;如果只存在1个节点,则不交换前后位置:

    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode p = new ListNode(0), q = p;
        p.next = head;
        head = head.next;
        while ((q = q.next) != null && q.next != null) {  //说明至少存在2个节点待交换,则进行节点交换
                p.next = q.next;
                q.next = p.next.next;
                p.next.next = q;
                p = q;
        }
        return head;
    }
55 / 55 test
cases passed. Runtime: 0 ms Your runtime beats 13.35% of javasubmissions.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: