LeetCode24-兩兩交換連結串列中的節點
阿新 • • 發佈:2018-12-08
最近學校在弄125年校慶,官方微信公眾號還推出了校慶頭像框的活動,我這個老臘肉自然是要來不知羞恥的湊個熱鬧啦!請各位看官看下圖,不喜勿噴哈,我心臟比較小,啊哈哈哈哈哈。
24-兩兩交換連結串列中的節點
給定一個連結串列,兩兩交換其中相鄰的節點,並返回交換後的連結串列。
例項:
給定1->2->3->4, 其結果為2->1->4->3
說明:
- 你的演算法只能使用常數的額外空間。
- 你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
這一題我剛開始是想用雙指標來解題的,即first指標指向給定的head指標表頭,second指標指向first指標的後一個節點,再新建一個指標專門順序接受second->first這兩個指標所對應的值,最後即可得所要結果。但這其中有個小障礙就是一定一定要處理好first和second指標的指向問題,因為這兩個指標都是指向head指標的,一旦沒有指向好,就得不出結果的。今天剛好有一筆友問了我這方面的問題,於是就想了一會兒終於是把之前留下的爛攤子給解決了,由於他是用java寫的,所以我就也用java寫了。
程式碼如下:
class Solution { public ListNode swapPairs(ListNode head) { ListNode virtual=new ListNode(0); if(head==null || head.next==null) return head; ListNode baseRear=virtual; ListNode rear=head; ListNode front=head.next; while(rear!=null && front!=null) { baseRear.next= new ListNode(front.val); baseRear.next.next = new ListNode(rear.val); baseRear=baseRear.next.next; if(front.next != null) { rear=front.next; front=rear.next; }else { rear = front = null; } } if(rear!=null) { baseRear.next= new ListNode(rear.val); baseRear=baseRear.next; } return virtual.next; } } public class JTest2 { public static void main(String[] args) { int head_list[] = {1, 2, 5, 4, 7}; ListNode head = new ListNode(0); ListNode head_copy = head; for (int i = 0; i < head_list.length; i++) { head_copy.next = new ListNode(head_list[i]); head_copy = head_copy.next; } Solution solu = new Solution(); ListNode result = solu.swapPairs(head.next); while (result != null) { System.out.println(result.val); result = result.next; } } }
下面是我那作圖一流的筆友提供的指標指向圖,很形象生動,方便大家理解。
執行效率當然也是棒棒噠!
還有一種方法是我用單指標解決的,當時就是被雙指標搞糊塗了,所以就想用單指標解決,但其實思想還是和雙指標的思想是一樣的,只不過我這兒是用單指標來分別表示first和second指標的,這兒就是用python寫的。
程式碼如下:
class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None: return [] head_copy = head head_sort = ListNode(0) head_sort_copy = head_sort while head_copy.next: head_sort_copy.next = ListNode(head_copy.next.val) head_sort_copy = head_sort_copy.next head_sort_copy.next = ListNode(head_copy.val) head_sort_copy = head_sort_copy.next if head_copy.next.next: head_copy = head_copy.next.next else: break if head_copy and head_copy.next is None: head_sort_copy.next = head_copy return head_sort.next if __name__ == '__main__': head_num = [2, 1, 3, 4, 8, 9] head = ListNode(0) head_copy = head for num in head_num: head_copy.next = ListNode(num) head_copy = head_copy.next result = Solution().swapPairs(head.next) while result: print(result.val) result = result.next
執行效率比上面的雙指標方法還要高些。