算法:链表的重排

LeetCode OJ: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}.

首先想的是遍历整个链表,然后迭代的将最后一个元素插入到首元素的后面,结果爆出来的是Time Limit Exceeded,测试用例是特别长的一段数字。

class Solution {
public:
    void reorderList(ListNode *head) {
        if((head == NULL) || (head->next == NULL))
            return ;
        ListNode *end, *pre_end;
        pre_end = end = head;
        while(end->next != NULL)
        {
            pre_end = end;
            end = end->next;
        }
            
        if(head->next != end)
        {
            end->next = head->next;
            head->next = end;
            pre_end->next = NULL; //刷题刷的恶心今天,这里一个小错误害的我调试半个小时
            
        }
        
        reorderList(end->next);
        
    }
};

后来想的如果时间复杂度不满足,那就要想方设法降低遍历的时间:

可以先将链表一分为二,然后将链表后半部分逆序,最后将后半部分的元素按插空法一个一个插入到链表的前半部分。

class Solution {
public:
    void reorderList(ListNode *head) {
        if((head == NULL) || (head->next == NULL) || (head->next->next == NULL))
            return ;
        ListNode *fast, *slow, *new_head, *reverseHead, *temp, *p;
        fast = slow = head;
        while((fast != NULL) && (fast->next != NULL))
        {
            slow = slow->next;
            fast = fast->next->next;
            
        }
        new_head = slow->next;
        slow->next = NULL;
        reverseHead = reverse_List(new_head);
        
        p = head;
        while((p != NULL) && (reverseHead != NULL))
        {
            temp = reverseHead;
            reverseHead = reverseHead->next;
            temp->next = p->next;
            p->next = temp;
            p = temp->next;
        }
        
    }
    
    ListNode * reverse_List(ListNode *head){
        ListNode *p, *q, *r;
        p = head;
        q = r = p->next;
        p->next = NULL;
    
        while(r)
        {
            q = r;
            r = q->next;
        
            q->next = p;
            p = q;
        }
        return p;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值