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}
.
题目分析:
这是一个链表重排序问题,其实只要能够做到链表倒序,然后一个个插进去就可以了,这样时间,空间复杂度都为o(n)
代码如下:
public static void reorderList(ListNode head) {
ListNode p=head;
int len=getlength(head);
if(len<=1) return ;
ListNode q=head;
ListNode newhead=null;
ListNode index=null;
while(q!=null)
{
ListNode x=new ListNode(q.val);
if(newhead==null)
{
newhead=x;
index=newhead;
}
else
{
x.next=index;
index=x;
newhead=x;
}
q=q.next;
}
ListNode m=head;
ListNode n=newhead;
if((len%2)==1)
{
for(int i=0;i<len/2;i++)
{
ListNode tmp1=n.next;
ListNode tmp2=m.next;
n.next=tmp2;
m.next=n;
n=tmp1;
m=tmp2;
}
m.next=null;
}
else
{
for(int i=0;i<len/2-1;i++)
{
ListNode tmp1=n.next;
ListNode tmp2=m.next;
n.next=tmp2;
m.next=n;
n=tmp1;
m=tmp2;
}
m.next=n;
n.next=null;
}
}
public static int getlength(ListNode head)
{
int num=0;
ListNode p=head;
while(p!=null)
{
num++;
p=p.next;
}
return num;
}
需要注意的地方为:1:链表处理要注意指向,不要出现死循环 2:奇数个和偶数个处理方式略有不同,注意区分