題目鏈接:24. 兩兩交換鏈表中的節(jié)點 - 力扣(LeetCode)
實際上是兩個兩個一組顛倒順序,可以用k=2使用【LeetCode熱題100】【鏈表】K 個一組翻轉鏈表-CSDN博客文章來源:http://www.zghlxwxcb.cn/news/detail-849990.html
但可以更簡單,就先看兩個,先取第二個的指針,遞歸顛倒第二個后面的節(jié)點,鏈接到第一個節(jié)點上,然后把第一個節(jié)點鏈接到第二個節(jié)點上,返回第二個節(jié)點指針文章來源地址http://www.zghlxwxcb.cn/news/detail-849990.html
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode *temp = head->next;
head->next = swapPairs(temp->next);
temp->next = head;
return temp;
}
};
到了這里,關于【LeetCode熱題100】【鏈表】兩兩交換鏈表中的節(jié)點的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!