您的位置:首页 > 其它

Reorder List

2015-08-10 22:22 155 查看
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}.

实现最终的链表需要三步:将链表分成前后两段,反转后半部分,合并两个链表。

public void reorderList(ListNode head) {
if(head==null&&head.next!=null)
return;
ListNode fast=head,slow=head;
while(fast!=null&&fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}
ListNode t1=slow.next;
slow.next=null;
ListNode t2=reverseList(t1);
ListNode t=head;
while(t2!=null){
ListNode t3=t.next,t4=t2.next;
t.next=t2;
t2.next=t3;
t=t3;
t2=t4;
}
}
public ListNode reverseList(ListNode head){
ListNode newHead=null;
while(head!=null){
ListNode t=head.next;
head.next=newHead;
newHead=head;
head=t;
}
return newHead;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: