-
Notifications
You must be signed in to change notification settings - Fork 2
/
24. Swap Nodes in Pairs.cpp
60 lines (56 loc) · 1.47 KB
/
24. Swap Nodes in Pairs.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode *dummy=new ListNode(0),*p=dummy;
dummy->next=head;
while(head!=NULL&&head->next!=NULL){
ListNode* tmp=head->next;
head->next=head->next->next;
tmp->next=head;
p->next=tmp;
p=head;
head=head->next;
}
return dummy->next;
}
};//通过引入一个*p->nexthead.使得能够输出最终指向
//第二种方法
class Solution2 {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL)
return head;
ListNode* dummy=new ListNode(0),*p=dummy;
dummy->next=head;
while(p){
p->next=reversePairs(p->next);
for(int i=1;p&&i<=2;i++)
p=p->next;
}
return dummy->next;
}
ListNode* reversePairs(ListNode* head){
if(head==NULL||head->next==NULL)
return head;
ListNode* pEnd=head;
int k=2;
while(pEnd&&k--){
pEnd=pEnd->next;
}
if(k>0)
return head;
ListNode* finalHead=pEnd;
while(head!=pEnd){
ListNode* tmp=head->next;
head->next=finalHead;
finalHead=head;
head=tmp;
}
return finalHead;
}
};
// 努力掌握第一种方法
//不会了啊
// 基本一次通过啊