题目:
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}
.
一看到这题我一开始联想到对链表进行排序那题,同样可以分为三个步骤:
1,寻找链表的中间节点(快慢指针)
2,对链表进行倒置
3,节点插入
代码如下:
public static void reorderList(ListNode head) {
if(head!=null&&head.next!=null)
{
ListNode middle=getMideeldofList(head);
ListNode next=middle.next;
middle.next=null;
ListNode backNode=ReverseList(next);
ListNode cur=head,cur1=backNode;
ListNode next1=null,next2=null;
while(cur!=null&&cur1!=null)
{
next1=cur.next;
next2=cur1.next;
cur.next=cur1;
cur1.next=next1;
cur=next1;
cur1=next2;
}
}
}
public static ListNode getMideeldofList(ListNode head)
{
if(head==null||head.next==null)
return head;
ListNode slow=head,fast=head;
while(fast!=null&&fast.next!=null)
{
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
public static ListNode ReverseList(ListNode head)
{
if(head==null||head.next==null)
return head;
ListNode fakeNode=new ListNode(-1);
fakeNode.next=head;
ListNode pre=fakeNode,cur=head.next,firstNode=head;
while(cur!=null)
{
ListNode next=cur.next;
cur.next=pre.next;
pre.next=cur;
cur=next;
}
firstNode.next=null;
return fakeNode.next;
}
第二种解法:
听过一句话,软件解决起来很复杂的问题有时候用硬件能够很轻松地解决,同样需要用复杂的代码实现的功能有时候通过选择恰当的数据结构能够很方便解决。
在这题中,我们可以通过把链表的节点放入一个栈中,通过这么一个步骤可以实现上面寻找中间节点和链表转置两个功能,接着就只需要进行节点插入的操作了。
代码:
public static void reorderList2(ListNode head) {
if(head==null||head.next==null)
return;
Stack<ListNode> stack=new Stack<>();
ListNode cur=head;
while(cur!=null)
{
stack.push(cur);
cur=cur.next;
}
int count=stack.size()/2;
cur=head;
ListNode nextNode=null,tempNode=null;
while(count>0)
{
tempNode=stack.pop();
nextNode=cur.next;
cur.next=tempNode;
tempNode.next=nextNode;
cur=nextNode;
count--;
}
if(nextNode!=null)
{
nextNode.next=null;
}
}