Skip to content

Commit 2393689

Browse files
authored
Merge pull request doocs#55 from xiapengchng/dev
Update solution 024 in cpp version with recursion
2 parents 89a210b + 8130f37 commit 2393689

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode* swapPairs(ListNode* head) {
12+
if(head==NULL||head->next==NULL)//递归的最小情况,链表为空,或者长度为1,直接返回
13+
return 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;
19+
}
20+
};
21+
22+

0 commit comments

Comments
 (0)