前言
题目: 24. 两两交换链表中的节点
文档: 代码随想录——两两交换链表中的节点
编程语言: C++
解题状态: 没画图,被绕进去了…
思路
思路还是挺清晰的,就是简单的模拟,但是一定要搞清楚交换的步骤,绕不清楚的时候最好画图来辅助解决问题。
代码
/**
* 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* dummyHead = new ListNode(0);
dummyHead -> next = head;
ListNode* cur = dummyHead;
while (cur -> next != nullptr && cur -> next -> next != nullptr) {
ListNode* tmp1 = cur -> next;
ListNode* tmp2 = cur -> next -> next -> next;
cur -> next = cur -> next -> next;
cur -> next -> next = tmp1;
cur -> next -> next -> next = tmp2;
cur = cur -> next -> next;
}
head = dummyHead -> next;
delete dummyHead;
return head;
}
};
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)