Skip to content

Commit ac735d9

Browse files
添加 0024.两两交换链表中的节点.md C语言递归版本
1 parent ded9ecf commit ac735d9

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

problems/0024.两两交换链表中的节点.md

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,21 @@ C:
9494
* struct ListNode *next;
9595
* };
9696
*/
97+
//递归版本
98+
struct ListNode* swapPairs(struct ListNode* head){
99+
//递归结束条件:头节点不存在或头节点的下一个节点不存在。此时不需要交换,直接返回head
100+
if(!head || !head->next)
101+
return head;
102+
//创建一个节点指针类型保存头结点下一个节点
103+
struct ListNode *newHead = head->next;
104+
//更改头结点+2位节点后的值,并将头结点的next指针指向这个更改过的list
105+
head->next = swapPairs(newHead->next);
106+
//将新的头结点的next指针指向老的头节点
107+
newHead->next = head;
108+
return newHead;
109+
}
97110

98-
111+
//迭代版本
99112
struct ListNode* swapPairs(struct ListNode* head){
100113
//使用双指针避免使用中间变量
101114
typedef struct ListNode ListNode;

0 commit comments

Comments
 (0)