Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
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
Given
{1,2,3,4}
, reorder it to {1,4,2,3}
.
Solution:
3 steps:
1.Cut the list to two halves.
2.Reverse the second half of the list
3.Insert the second half nodes to first half of the list
Time complexity: O(n) in place
public void reorderList(ListNode head) {
if(head==null || head.next==null) return;
ListNode walker=head;
ListNode runner=head;
while(runner!=null && runner.next!=null){
walker=walker.next;
runner=runner.next.next;
}
ListNode tail=walker.next;
if(tail==null) return;
while(tail.next!=null){
ListNode cur=tail.next;
tail.next=cur.next;
cur.next=walker.next;
walker.next=cur;
}
ListNode pre=head;
while(walker.next!=null){
ListNode cur=walker.next;
walker.next=cur.next;
cur.next=pre.next;
pre.next=cur;
pre=cur.next;
}
}
No comments:
Post a Comment