#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
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* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while (cur->next != nullptr && cur->next->next != nullptr) {
ListNode* a = cur->next;
ListNode* b = cur->next->next;
ListNode* c = cur->next->next->next;
a->next = c;
b->next = a;
cur->next = b;
cur = cur->next->next;
}
return dummyHead->next;
}
};
int main() {
Solution test;
ListNode* a = new ListNode(1);
a->next= new ListNode(2);
a->next->next = new ListNode(3);
a->next->next->next= new ListNode(4);
ListNode* ans = test.swapPairs(a);
while (ans != nullptr) {
cout << ans->val << endl;
ans = ans->next;
}
return 0;
}
24. 两两交换链表中的节点
最新推荐文章于 2024-07-20 09:21:06 发布