LeetCode-链表-24. 两两交换链表中的节点
生活随笔
收集整理的這篇文章主要介紹了
LeetCode-链表-24. 两两交换链表中的节点
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
24. 兩兩交換鏈表中的節點
思路:使用一個頭節點,然后用cur指針指向頭
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/ class Solution { public:ListNode* swapPairs(ListNode* head) {ListNode* dummy = new ListNode(0); //新建一個頭節點dummy->next = head; //下一個指針指向鏈表頭ListNode* cur = dummy;while(cur->next!=nullptr&&cur->next->next!=nullptr){ListNode* next = cur->next;ListNode* nextNext = cur->next->next;ListNode* next2Next = cur->next->next->next;cur->next = nextNext; //步驟一cur->next->next = next; //步驟二cur->next->next->next = next2Next; //步驟三cur = cur->next->next; //移動當前鏈表指針到下兩個}return dummy->next;} };總結
以上是生活随笔為你收集整理的LeetCode-链表-24. 两两交换链表中的节点的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode-二分查找-374. 猜
- 下一篇: LeetCode-二分查找-278. 第