-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24.cpp
30 lines (27 loc) · 773 Bytes
/
24.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
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) {}
};
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode(0, head);
ListNode* cur = dummy;
ListNode* tmp;
while (cur->next && cur->next->next) {
tmp = cur->next->next;
cur->next->next = cur->next->next->next;
tmp->next = cur->next;
cur->next = tmp;
cur = cur->next->next;
}
return dummy->next;
}
int main() {
ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4))));
ListNode* swapped = swapPairs(head);
return 0;
}