您的位置:首页 > 编程语言 > Java开发

[leetcode] Reorder List

2014-09-15 13:49 211 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm java leetcode