LeetCode Ex24 Swap Nodes in Pairs

Swap Nodes in Pairs

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.

题目

交换链表中每两个相邻节点,跟交换元素一样,只需要注意指针指向即可。

迭代方法

    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode p1 = dummy;
        while (p1.next != null && p1.next.next != null) {
            ListNode first = p1.next;
            ListNode second = p1.next.next;
            first.next = second.next;
            p1.next = second;
            second.next = first;
            p1 = p1.next.next;
        }
        return dummy.next;
    }

递归方法

    public ListNode swapPairs(ListNode head) {
        if ((head == null)||(head.next == null))
            return head;
        ListNode n = head.next;
        head.next = swapPairs(head.next.next);
        n.next = head;
        return n;
    }

猜你喜欢

转载自blog.csdn.net/weixin_34023982/article/details/87528958