TypechoJoeTheme

IT技术分享

统计

[LeetCode 24] Swap Nodes in Pairs [Java]

2017-11-23
/
0 评论
/
600 阅读
/
正在检测是否收录...
11/23

1. Description

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

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

2. Example

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

3. Code

public class LeetCode0024 {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public ListNode swapPairs(ListNode head)
    {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        swap(dummy);
        return dummy.next;
    }

    private void swap(ListNode p1)
    {
        if (p1 == null) {
            return;
        }
        ListNode p2 = p1.next;
        if (p2 == null) {
            return;
        }

        ListNode p3 = p2.next;
        if (p3 == null) {
            return;
        }

        p2.next = p3.next;
        p3.next = p2;
        p1.next = p3;       
        swap(p2);
    }
}
Linked
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1276/(转载时请注明本文出处及文章链接)