forked from coderchen/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwapNodesInPairs.cpp
44 lines (39 loc) · 945 Bytes
/
SwapNodesInPairs.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
//递归求解
ListNode *swapPairs_recursion(ListNode *head) {
if (!head || !head->next) return head;
ListNode* newHead = head->next;
head->next = swapPairs(newHead->next);
newHead->next = head;
return newHead;
}
//非递归求解
ListNode *swapPairs(ListNode* head) {
ListNode* newHead = nullptr;
ListNode** pp = &newHead;
while (head) {
if (!head->next) {
*pp = head;
break;
} else {
*pp = head->next;
head->next = (*pp)->next;
(*pp)->next = head;
pp = &head->next;
head = head->next;
}
}
return newHead;
}
};
int main()
{
return 0;
}