《leetCode》:Reorder List

题目

Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

思路一:报超时错误

利用两个循环来做,即每次将链表中最后一个节点找到并插入到相应的位置。
时间复杂度为:O(n^2)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
void reorderList(struct ListNode* head) {
    if(head==NULL||head->next==NULL){
        return;
    }
    //用两个for循环来做
    struct ListNode* cur=head;
    struct ListNode* next=NULL;
    struct ListNode* final=NULL;
    struct ListNode* preFinal=NULL;
    while(cur->next!=NULL&&cur->next->next!=NULL){
        next=cur->next;//保存下一个节点 
        //使得node指向最后一个节点的位置 
        final=cur;
        preFinal=NULL;
        while(final->next!=NULL){
            preFinal=final;
            final=final->next;
        }
        preFinal->next=NULL;
        cur->next=final;
        final->next=next;
        cur=next; 
    } 
}

思路二

先找到即将要插入的后面一半的链表的起始点,然后将其翻转作为一个新链表,最后合并即为所求

实现代码如下:

//合并两个链表 
void combineList(struct ListNode* head,struct ListNode* newHead){
    if(head==NULL){
        head=newHead;
        return ;
    } 
    if(newHead==NULL){
        return;
    }
    struct ListNode* cur1=head;
    struct ListNode* next1=NULL;
    struct ListNode* cur2=newHead;
    struct ListNode* next2=NULL;
    while(cur1!=NULL&&cur2!=NULL){
        next1=cur1->next;
        next2=cur2->next;
        cur1->next=cur2;
        if(next1!=NULL){
            cur2->next=next1;
        }       
        cur1=next1;
        cur2=next2;
    }   
} 
struct ListNode* reverseList(struct ListNode* head){
    if(head==NULL){
        return NULL;
    }
    struct ListNode* pre=NULL;
    struct ListNode* cur=head;
    struct ListNode* next=NULL;
    while(cur->next!=NULL){
        next=cur->next;
        cur->next=pre;
        pre=cur;
        cur=next;
    }
    cur->next=pre;//把最后一个节点连接上 
    return cur;
}
/*
思路:先找到即将要插入的后面一半的链表的起始点,然后将其翻转,最后合并即为所有 
*/
void reorderList(struct ListNode* head) {
    if(head==NULL||head->next==NULL){
        return;
    }
    struct ListNode* slow=head;
    struct ListNode* fast=head;
    while(fast!=NULL&&fast->next!=NULL){
        slow=slow->next;
        fast=fast->next->next;
    } 
    //翻转slow后面的节点成为一个新的链表 
    struct ListNode* node=reverseList(slow->next);
    slow->next=NULL;
    //合并
    combineList(head,node);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值