24. Nodes in two exchange linked list

Given a linked list, two pairs exchange the adjacent nodes and return the linked list after exchange.

Example:

Given 1 - > 2 - > 3 - > 4, you should return 2 - > 1 - > 4 - > 3

Explain:

    Your algorithm can only use constant extra space.
    You can't just change the internal values of nodes, but you need to actually exchange nodes.

The requirement of exchanging from the front to the back means that the next point of the second point of each group should have been exchanged, so it's natural to think of recursion.

public class SwapPairs2 {
    public ListNode swapPairs(ListNode head) {
        if(head==null) return null;
        if(head.next==null) return head;//Singular condition
        ListNode temp = head.next;
        head.next = swapPairs(temp.next);
        temp.next = head;
        return temp;//This is actually the first position in a group
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        listNode.next = new ListNode(2);
        listNode.next.next = new ListNode(3);
        listNode.next.next.next = new ListNode(4);

        ListNode listNode2 = new SwapPairs2().swapPairs(listNode);
        while(listNode2!=null) {
            System.out.print(listNode2.val + " ");
            listNode2 = listNode2.next;

        }
    }

}

But the efficiency of using recursion is relatively low. Here is the non recursion method.
When I write, the second point stuck in a group should be the one after exchange, that is, the second one of the second group. Later, it was understood that a pointer should be set to let the second of the previous group point to the first of the updated group each time the next group is exchanged.

public class SwapPairs2 {
    public ListNode swapPairs(ListNode head) {
        if(head==null || head.next==null) return head;
        ListNode cur = head;
        ListNode ret = head.next;//'head pointer' to return
        ListNode pre = null;//Used to adjust the direction of the second of the previous group
        while(cur!=null && cur.next!=null) {
            ListNode next = cur.next;
            cur.next = next.next;
            next.next = cur;
            if(pre==null) {
                pre = cur;
            }
            else {
                pre.next = next;
                pre = cur;
            }
            cur = cur.next;
        }
        return ret;
    }

    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        listNode.next = new ListNode(2);
        listNode.next.next = new ListNode(3);
        listNode.next.next.next = new ListNode(4);

        ListNode listNode2 = new SwapPairs2().swapPairs(listNode);
        while(listNode2!=null) {
            System.out.print(listNode2.val + " ");
            listNode2 = listNode2.next;

        }
    }

}

Posted by BizBoy on Tue, 31 Dec 2019 01:06:00 -0800