LeetCode--24. Swap Nodes in Pairs
阿新 • • 發佈:2018-11-25
題目連結: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)嗎?