您的位置:首页 > 编程语言 > Java开发

Leetcode-Reorder List

2016-10-31 17:53 309 查看
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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}
.
这个题目一开始理解错题意了,我以为是inverse链表。这个问题的本质是首先将链表切分为前后两段,然后将后一段链表进行inverse,然后把两端链表互相插入合并。Your runtime beats
65.93% of java submissions.
public class Solution {
public void reorderList(ListNode head) {
if(head != null && head.next != null && head.next.next != null){
ListNode p1 = head,p2 = head;
while(p2 !=null && p2.next != null){
p1 = p1.next;
p2 = p2.next.next;
}

ListNode head2 = p1.next,p3 = null,head1 = head;
p1.next = null;
p1 = null;p2 = head2;p3 = head2.next;
while( p2 != null && p2.next != null){
p2.next = p1;
p1 = p2;
p2 = p3;
p3 = p3.next;
}
p2.next = p1; head2 = p2;
p1 = head1.next; p2 = head2;
ListNode searchNode = head;
boolean flag = true;
while( p2 != null){
if(flag){
searchNode.next = p2;
p2 = p2.next;
}else{
searchNode.next = p1;
p1 = p1.next;
}
searchNode = searchNode.next;
flag = !flag;
}
searchNode.next = p1;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 算法