码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_143_Reorder List

时间:2015-02-07 15:58:54      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:reorder list   stack   peek   链表      

描述:

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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 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;
		 }
	 }


结果:

leetcode_143_Reorder List

标签:reorder list   stack   peek   链表      

原文地址:http://blog.csdn.net/mnmlist/article/details/43603757

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!