mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加 0024.两两交换链表中的节点.md C语言递归版本
This commit is contained in:
@ -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;
|
||||
|
Reference in New Issue
Block a user