24. 两两交换链表中的节点
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/submissions/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
题目分析
采用虚结点。
/**
* 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) {
// if(head == nullptr || head->next = nullptr) return head;
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *cur = dummy;
while(cur->next != nullptr && cur->next->next != nullptr){
ListNode *next = cur->next;
cur->next = cur->next->next;
next->next = next->next->next;
cur->next->next = next;
cur = next;
}
return dummy->next;
}
};