C++實(shí)現(xiàn)LeetCode(24.成對(duì)交換節(jié)點(diǎn))
[LeetCode] 24. Swap Nodes in Pairs 成對(duì)交換節(jié)點(diǎn)
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given
1->2->3->4
, you should return the list as
2->1->4->3.
這道題不算難,是基本的鏈表操作題,我們可以分別用遞歸和迭代來實(shí)現(xiàn)。對(duì)于迭代實(shí)現(xiàn),還是需要建立 dummy 節(jié)點(diǎn),注意在連接節(jié)點(diǎn)的時(shí)候,最好畫個(gè)圖,以免把自己搞暈了,參見代碼如下:
解法一:
class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode *dummy = new ListNode(-1), *pre = dummy; dummy->next = head; while (pre->next && pre->next->next) { ListNode *t = pre->next->next; pre->next->next = t->next; t->next = pre->next; pre->next = t; pre = t->next; } return dummy->next; } };
遞歸的寫法就更簡潔了,實(shí)際上利用了回溯的思想,遞歸遍歷到鏈表末尾,然后先交換末尾兩個(gè),然后依次往前交換:
解法二:
class Solution { public: ListNode* swapPairs(ListNode* head) { if (!head || !head->next) return head; ListNode *t = head->next; head->next = swapPairs(head->next->next); t->next = head; return t; } };
解法三:
class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } ListNode newHead = head.next; head.next = swapPairs(newHead.next); newHead.next = head; return newHead; } }
到此這篇關(guān)于C++實(shí)現(xiàn)LeetCode(24.成對(duì)交換節(jié)點(diǎn))的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)成對(duì)交換節(jié)點(diǎn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C/C++字符串函數(shù)之復(fù)制函數(shù)詳解
下面小編就為大家?guī)硪黄狢/C++字符串函數(shù)之復(fù)制函數(shù)詳解。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-09-09一些語言的按行讀取文件的代碼實(shí)現(xiàn)小結(jié)
這篇文章主要介紹了一些語言的按行讀取文件的代碼實(shí)現(xiàn)小結(jié),這里羅列了Java和C語言和C++以及PHP的實(shí)現(xiàn)需要的朋友可以參考下2015-08-08