From 9d09b11d56722748e00d3647cdcd228793baaa66 Mon Sep 17 00:00:00 2001 From: Guanzhong Pan Date: Wed, 26 Jan 2022 09:26:03 +0000 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200143.=E9=87=8D=E6=8E=92?= =?UTF-8?q?=E9=93=BE=E8=A1=A8.md=20C=E8=AF=AD=E8=A8=80=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0143.重排链表.md | 68 +++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/problems/0143.重排链表.md b/problems/0143.重排链表.md index 4ea9cb97..00622623 100644 --- a/problems/0143.重排链表.md +++ b/problems/0143.重排链表.md @@ -439,7 +439,75 @@ var reorderList = function(head, s = [], tmp) { } ``` +### C +方法三:反转链表 +```c +//翻转链表 +struct ListNode *reverseList(struct ListNode *head) { + if(!head) + return NULL; + struct ListNode *preNode = NULL, *curNode = head; + while(curNode) { + //创建tempNode记录curNode->next(即将被更新) + struct ListNode* tempNode = curNode->next; + //将curNode->next指向preNode + curNode->next = preNode; + //更新preNode为curNode + preNode = curNode; + //curNode更新为原链表中下一个元素 + curNode = tempNode; + } + return preNode; +} +void reorderList(struct ListNode* head){ + //slow用来截取到链表的中间节点(第一个链表的最后节点),每次循环跳一个节点。fast用来辅助,每次循环跳两个节点 + struct ListNode *fast = head, *slow = head; + while(fast && fast->next && fast->next->next) { + //fast每次跳两个节点 + fast = fast->next->next; + //slow每次跳一个节点 + slow = slow->next; + } + //将slow->next后的节点翻转 + struct ListNode *sndLst = reverseList(slow->next); + //将第一个链表与第二个链表断开 + slow->next = NULL; + //因为插入从curNode->next开始,curNode刚开始已经head。所以fstList要从head->next开始 + struct ListNode *fstLst = head->next; + struct ListNode *curNode = head; + + int count = 0; + //当第一个链表和第二个链表中都有节点时循环 + while(sndLst && fstLst) { + //count为奇数,插入fstLst中的节点 + if(count % 2) { + curNode->next = fstLst; + fstLst = fstLst->next; + } + //count为偶数,插入sndList的节点 + else { + curNode->next = sndLst; + sndLst = sndLst->next; + } + //设置下一个节点 + curNode = curNode->next; + //更新count + ++count; + } + + //若两个链表fstList和sndLst中还有节点,将其放入链表 + if(fstLst) { + curNode->next = fstLst; + } + if(sndLst) { + curNode->next = sndLst; + } + + //返回链表 + return head; +} +``` -----------------------