Skip to content

Commit 8130f37

Browse files
author
xiapengchng
committed
Update solution 024 in cpp with recursion
1 parent 7a03ae2 commit 8130f37

File tree

1 file changed

+7
-23
lines changed

1 file changed

+7
-23
lines changed

solution/024.Swap Nodes in Pairs/Solution.cpp

Lines changed: 7 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,14 @@
99
class Solution {
1010
public:
1111
ListNode* swapPairs(ListNode* head) {
12-
if(head==NULL||head->next==NULL)
12+
if(head==NULL||head->next==NULL)//递归的最小情况,链表为空,或者长度为1,直接返回
1313
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;
3219
}
33-
34-
3520
};
36-
37-
21+
3822

0 commit comments

Comments
 (0)