File tree Expand file tree Collapse file tree 1 file changed +7
-23
lines changed
solution/024.Swap Nodes in Pairs Expand file tree Collapse file tree 1 file changed +7
-23
lines changed Original file line number Diff line number Diff line change 9
9
class Solution {
10
10
public:
11
11
ListNode* swapPairs (ListNode* head) {
12
- if (head==NULL ||head->next ==NULL )
12
+ if (head==NULL ||head->next ==NULL )// 递归的最小情况,链表为空,或者长度为1,直接返回
13
13
return head;
14
- ListNode *real_head=head->next ;
15
-
16
-
17
- ListNode * tw=head->next ;
18
- head->next =head->next ->next ;
19
- tw->next =head;
20
- ListNode *tail=head;
21
- head=tw->next ->next ;
22
- while (head!=NULL &&head->next !=NULL )
23
- {
24
- tw=head->next ;
25
- head->next =head->next ->next ;
26
- tw->next =head;
27
- tail->next =tw;
28
- tail=head;
29
- head=tw->next ->next ;
30
- }
31
- return real_head;
14
+ ListNode *temp=head->next ;// 定义temp为head->next的node
15
+ ListNode *nextChain=swapPairs (head->next ->next );// 递归调用得到head->next->next链表交换结果
16
+ head->next =nextChain;// head的next指向递归后的结果
17
+ temp->next =head;// temp也就是之前的head->next节点指向head,那么现在的head为temp
18
+ return temp;
32
19
}
33
-
34
-
35
20
};
36
-
37
-
21
+
38
22
You can’t perform that action at this time.
0 commit comments