Skip to content

Commit

Permalink
添加 0024.两两交换链表中的节点.md C语言递归版本
Browse files Browse the repository at this point in the history
  • Loading branch information
KingArthur0205 committed Jan 2, 2022
1 parent ded9ecf commit ac735d9
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion problems/0024.两两交换链表中的节点.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,21 @@ C:
* struct ListNode *next;
* };
*/
//递归版本
struct ListNode* swapPairs(struct ListNode* head){
//递归结束条件:头节点不存在或头节点的下一个节点不存在。此时不需要交换,直接返回head
if(!head || !head->next)
return head;
//创建一个节点指针类型保存头结点下一个节点
struct ListNode *newHead = head->next;
//更改头结点+2位节点后的值,并将头结点的next指针指向这个更改过的list
head->next = swapPairs(newHead->next);
//将新的头结点的next指针指向老的头节点
newHead->next = head;
return newHead;
}


//迭代版本
struct ListNode* swapPairs(struct ListNode* head){
//使用双指针避免使用中间变量
typedef struct ListNode ListNode;
Expand Down

0 comments on commit ac735d9

Please sign in to comment.