學渣帶你刷Leetcode143. 重排鏈表

題目描述

給定一個單鏈表 L:L0→L1→…→Ln-1→Ln ,
將其重新排列後變爲: L0→Ln→L1→Ln-1→L2→Ln-2→…

你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。

示例 1:

給定鏈表 1->2->3->4, 重新排列爲 1->4->2->3.
示例 2:

給定鏈表 1->2->3->4->5, 重新排列爲 1->5->2->4->3.

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reorder-list
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

白話題目:
 

算法:

 

詳細解釋關注 B站  【C語言全代碼】學渣帶你刷Leetcode 不走丟 https://www.bilibili.com/video/BV1C7411y7gB

C語言完全代碼

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


void reorderList(struct ListNode* head){
if(!head||head->next==NULL||head->next->next==NULL) return head;
else{
int i,len=0;
struct ListNode *p=head,*q=head,*r,*m,*n;
while(p)
{
    p=p->next;
    len++;
}
for(i=1;i<(len/2+1);i++) q=q->next;
p=q->next;
q->next=NULL;
r=(struct ListNode*)malloc(sizeof(struct ListNode));
r->next=NULL;
while(p)
{
    q=p->next;
    p->next=r->next;
    r->next=p;
    p=q;
}
q=head;
p=r->next;
while(p)
{
    m=p->next;
    n=q->next;
    p->next=q->next;
    q->next=p;
    p=m;
    q=n;
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章