LeetCode--24. Swap Nodes in Pairs

题目链接:https://leetcode.com/problems/swap-nodes-in-pairs/

思路类似于逆转单链表(https://blog.csdn.net/To_be_to_thought/article/details/83930978)找出循环不变式

思路具体如图:

                            

循环不变式提炼如下:

            rear.next=front.next;
            baseRear.next=front;
            front.next=rear;
            baseRear=rear;
            front=rear.next;
            rear=front.next;

代码如下:

class Solution {
    public ListNode swapPairs(ListNode head) {
        
        ListNode virtual=new ListNode(0);
        virtual.next=head;
        if(head==null || head.next==null)
            return head;
        ListNode baseRear=virtual;
        ListNode rear=head;
        ListNode front=head.next;
        
        while(front.next!=null && front.next.next!=null)
        {
            rear.next=front.next;
            baseRear.next=front;
            front.next=rear;
            baseRear=rear;
            front=rear.next;
            rear=front.next;
        }
        
        rear.next=front.next;
        baseRear.next=front;
        front.next=rear;
         
        return virtual.next;
    }
}

但是运行“Time Limited Exceed”,不是只有空间复杂度限制吗?真是一顿操作猛如虎,啪啪打脸!!!

在Discussion中看到一种代码十分简洁的递归解法,这个解法真妖孽!!!:

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null)
            return head;
        
        
        ListNode prev = null;
        ListNode curr = head;
        ListNode next = head.next;
        
        ListNode newHead = next;
        
        curr.next = swapPairs(next.next);
        next.next = curr;
            
       return newHead;
    }
}

但他妈递归的栈空间不是O(n)吗?

猜你喜欢

转载自blog.csdn.net/To_be_to_thought/article/details/84480476