-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathswap_node_pairs.cpp
More file actions
50 lines (40 loc) · 1.11 KB
/
swap_node_pairs.cpp
File metadata and controls
50 lines (40 loc) · 1.11 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "iostream"
#include "vector"
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) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* one = head, *two = head->next, *three = head->next->next;
two->next = one;
one->next = swapPairs(three);
return two;
}
// 迭代的方式
ListNode* swapPairs1(ListNode* head) {
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* p = dummy;
while (p->next && p->next->next) {
ListNode* prev = p->next, *back = p->next->next;
prev->next = back->next;
back->next = prev;
p->next = back;
p = p->next->next;
}
return dummy->next;
}
};
// 1 2 3 4
// p prev back