标签:reorder list stack peek 链表 栈
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}.
public void reorderList(ListNode head) {
if(head==null||head.next==null)
return;
ListNode pListNode=head,tempListNode=null;
Stack<ListNode>stack=new Stack<ListNode>();
int count=0,i=0;
while(pListNode!=null)
{
count++;
pListNode=pListNode.next;
}
int subLen=count/2+1;
pListNode=head;
for(i=1;i<subLen;i++)
pListNode=pListNode.next;
tempListNode=pListNode.next;
pListNode.next=null;
while(tempListNode!=null)
{
stack.push(tempListNode);
tempListNode=tempListNode.next;
}
pListNode=head;
while(!stack.empty())
{
tempListNode=stack.peek();
stack.pop();
tempListNode.next=pListNode.next;
pListNode.next=tempListNode;
pListNode=tempListNode.next;
}
}标签:reorder list stack peek 链表 栈
原文地址:http://blog.csdn.net/mnmlist/article/details/43603757