mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
添加 0143.重排链表.md C语言解法
This commit is contained in:
@ -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;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user