题目:
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}
.
分析:
- Break list in the middle to two lists (use fast & slow pointers)
- Reverse the order of the second list
- Merge two list back together
public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next==null)
{
return;
}
ListNode walker = head;
ListNode runner = head;
while(runner.next!=null && runner.next.next!=null)
{
walker = walker.next;
runner = runner.next.next;
}
ListNode head1 = head;
ListNode head2 = walker.next;
walker.next = null;
head2 = reverse(head2);
while(head1!=null && head2!=null)
{
ListNode next = head2.next;
head2.next = head1.next;
head1.next = head2;
head1 = head2.next;
head2 = next;
}
}
private ListNode reverse(ListNode head)
{
ListNode pre = null;
ListNode cur = head;
while(cur!=null)
{
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}