C++實(shí)現(xiàn)LeetCode(24.成對交換節(jié)點(diǎn))
[LeetCode] 24. Swap Nodes in Pairs 成對交換節(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)。對于迭代實(shí)現(xiàn),還是需要建立 dummy 節(jié)點(diǎn),注意在連接節(jié)點(diǎn)的時候,最好畫個圖,以免把自己搞暈了,參見代碼如下:
解法一:
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í)際上利用了回溯的思想,遞歸遍歷到鏈表末尾,然后先交換末尾兩個,然后依次往前交換:
解法二:
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.成對交換節(jié)點(diǎn))的文章就介紹到這了,更多相關(guān)C++實(shí)現(xiàn)成對交換節(jié)點(diǎn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Linux?C/C++實(shí)現(xiàn)顯示NIC流量統(tǒng)計(jì)信息
NIC流量統(tǒng)計(jì)信息是由操作系統(tǒng)維護(hù)的,當(dāng)數(shù)據(jù)包通過NIC傳輸時,操作系統(tǒng)會更新相關(guān)的計(jì)數(shù)器,通過讀取這些計(jì)數(shù)器,我們可以獲得關(guān)于網(wǎng)絡(luò)流量的信息,下面我們就來學(xué)習(xí)一下如何通過C/C++實(shí)現(xiàn)顯示NIC流量統(tǒng)計(jì)信息吧2024-01-01
手把手帶你學(xué)習(xí)C++的數(shù)據(jù)類型
這篇文章主要為大家介紹了C++的數(shù)據(jù)類型,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助,希望能夠給你帶來幫助2021-11-11
C語言進(jìn)階之字符串查找?guī)旌瘮?shù)詳解
字符串是一種非常重要的數(shù)據(jù)類型,但是C語言不存在顯式的字符串類型,C語言中的字符串都以字符串常量的形式出現(xiàn)或存儲在字符數(shù)組中,下面這篇文章主要給大家介紹了關(guān)于C語言進(jìn)階之字符串查找?guī)旌瘮?shù)的相關(guān)資料,需要的朋友可以參考下2023-01-01
Qt為exe添加ico圖片的簡單實(shí)現(xiàn)步驟
這篇文章主要給大家介紹了關(guān)于Qt為exe添加ico圖片的簡單實(shí)現(xiàn)步驟,通過文中介紹的方法可以幫助大家實(shí)現(xiàn)這個自定義exe圖標(biāo)的效果,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07

