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}.
Idea: First split the linked list to two half at point Ln/2. Then reverse the second half. Then we have a list like this:
L0 -> L1 ->... ->Ln/2-> Ln/2+1 <-Ln/2+2... <-Ln, where Ln/2+1.next=null. Then we merge the list from the two ends L0 and Ln one by one, e.g. L0 -> Ln -> L1 -> Ln-1 -> ... -> Ln/2 -> Ln/2+1.
Time: O(n) Space: O(n) (since the reverse of the second half is recursion which needs a O(n) stack).
Code:
public class Solution {
public ListNode reverseList(ListNode head)
{
if(head==null||head.next==null)
return head;
reverseList(head.next).next=head;
head.next=null;
return head;
}
public void reorderList(ListNode head) {
if(head==null||head.next==null)
return;
ListNode slower=head;
ListNode faster=head;
while(faster.next!=null)
{
faster=faster.next;
slower=slower.next;
if(faster.next!=null)
faster=faster.next;
}
reverseList(slower);
ListNode cur=head;
while(faster!=slower)
{
ListNode fasterTmp=faster.next;
faster.next=cur.next;
cur.next=faster;
faster=fasterTmp;
cur=cur.next.next;
}
}
}
No comments:
Post a Comment