public void reorderList(ListNode head) {
if(head == null || head.next == null)
return;
ListNode fast, slow, pre = null;
slow = fast = head;
while(fast != null && fast.next != null)
{
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
if(pre != null) pre.next = null;
ListNode p = slow, pp = null; //Reverse
while(p != null)
{
ListNode pn = p.next;
p.next = pp;
pp = p;
p = pn;
}
p = head;
ListNode p2 = pp;//Merge p, p2; p is longer or equal to p2
while(p2 != null && p != null)
{
ListNode p2n = p2.next;
ListNode pn = p.next;
p.next = p2;
if(pn != null) //p is exhausted
{
p2.next = pn;
}
p = pn;
p2 = p2n;
}
}
[leetcode] Reorder List
最新推荐文章于 2024-05-31 10:46:10 发布