143. 重排链表

题目:. - 力扣(LeetCode)

思路:找中间节点,将中间节点之后的节翻转,然后遍历中间节点前的节点的时候插入翻转后的节点

贴上代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 struct ListNode* reverse(struct ListNode* head){
    struct ListNode* prev=NULL;
    struct ListNode* cur=head;
    struct ListNode* Next=cur->next;
    while(true){
        cur->next=prev;
        if(Next==NULL){
            break;
        }
        prev=cur;
        cur=Next;
        Next=Next->next;
    }
    return cur;
}
void reorderList(struct ListNode* head) {
    //一个或两个节点不需要排
    if(head->next==NULL||head->next->next==NULL){
        return;
    }
    //找中间节点位置
    int len=0;
    struct ListNode* cur=head;
    while(cur){
        len++;
        cur=cur->next;
    }
    if(len%2==0){
        len=len/2;
    }else{
        len=len/2+1;
    }
    //将cur置于翻转处
    cur=head;
    struct ListNode* prev=NULL;
    while(len--){
        prev=cur;
        cur=cur->next;
    }
    prev->next=NULL;
    //翻转后半部分
    struct ListNode* nhead=reverse(cur);
    //合并
    cur=head;
    struct ListNode* Next=NULL;
    struct ListNode* nNext=NULL;
    while(nhead){
        Next=cur->next;
        nNext=nhead->next;
        cur->next=nhead;
        nhead->next=Next;
        nhead=nNext;
        cur=Next;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值