leetcode--Reorder List

来源:互联网 发布:南方易学软件 编辑:程序博客网 时间:2024/05/21 20:27

143.题目

Given a singly linked list L: L0?L1?…?Ln-1?Ln,reorder it to: L0?Ln?L1?Ln-1?L2?Ln-2?…ExampleGiven {1,2,3,4}, reorder it to {1,4,2,3}.

第一反应写的代码

class Solution {    public void reorderList(ListNode head) {        if(head == null) return;        if(head.next == null) return;        ListNode pre = head,preLast = head.next;        if(preLast.next == null) return;        while(preLast.next != null){            pre = pre.next;            preLast = pre.next;        }        ListNode next = head.next;        head.next = preLast;        preLast.next = next;        pre.next = null;        reorderList(next);        return;    }}

总共13组测试用例,跑过了12组,最后一组特别大的显示Time Limit Exceeded
改进……
1.可以找list的中心,从中心分为两个list;
2.对后半部分的实现从后指向前;
3.剩下两个list插空填充就行了。
下面是实现:

public void reorderList(ListNode head) {        if(head == null || head.next == null) return;        ///find the middle        ListNode p1 = head;        ListNode p2 = head;        while(p2.next != null && p2.next.next != null){            p1 = p1.next;            p2 = p2.next.next;        }        if(p2.next != null)            p2 = p2.next;        //p1 in the middle of the list        //p2 last in the list        //reverse the latter half of the list 1->2->3->4->5->6 to 1->2->3<-4<-5<-6        ListNode preCurrent = p1;        ListNode current = p1.next;        //if(p1 != head)        p1.next = null;        while(p1 != head && current != null){            ListNode k1 = current.next;            current.next = preCurrent;            preCurrent = current;            current = k1;        }        //merge two list 1->2->3 6->5->4->3        ListNode tmp1 = head;        ListNode tmp2 = p2;        while(tmp1 != tmp2 && tmp1 != null && tmp2 != null){            ListNode k1 = tmp1.next;            ListNode k2 = tmp2.next;            tmp1.next = tmp2;            tmp2.next = k1;            tmp1 = k1;            tmp2 = k2;        }    }
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 实木门上的伸缩缝太深怎么办 mac点关机没反应怎么办 被压倒扁的易拉罐怎么办 白色车漏底漆了怎么办 客厅对着卧室门怎么办 老公不上进还懒怎么办 二胡按弦手指分不开怎么办 酷塑做完后疼痛怎么办 冷冻治疗后水泡破了怎么办 冷冻治疗的水泡破了怎么办? 冷冻治疗水泡破了怎么办 脚上冷冻后起泡怎么办 刺猴冷冻后起泡怎么办 隔壁太吵怎么办阴招 楼上有小孩太吵怎么办 捷达小水管睹了怎么办 楼房下水管冻了怎么办 一楼地面很潮湿怎么办 新房子地面有裂缝怎么办 地砖下面的下水管漏水怎么办 速冻饺子冻在一起了怎么办 牛排泡水解冻了怎么办 饺子都粘一起了怎么办 把桃子放冷冻了怎么办 抖音小视频连不上网怎么办 网络视频连不上网怎么办 苹果8视频不清晰怎么办 乳疮腐烂还臭怎么办 冰箱肉腐烂很臭怎么办 指环扣松了怎么办视频 奇迹mu端游杀人了怎么办 奇迹最强者号找不着了怎么办 v领地退不了押金怎么办 全民奇迹sf钻石变负数怎么办 电脑上的新建没有了怎么办 火车上行李箱砸人怎么办 违建拆除后怎么办房产证 外地车遇到限号怎么办 双号限行 违了怎么办 下高速当地限行怎么办 下高速发现限号怎么办