首页 > 编程语言 > 详细

[LeetCode][Java] Partition List

时间:2015-07-19 13:26:15      阅读:270      评论:0      收藏:0      [点我收藏+]

题目:

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

题意:

给定一个链表和一个值x,分割链表使得比x小的节点都在大于或等于x的节点的前面。

你需要分别在这两个分割的部分中保持节点原始的相对顺序。

比如,

给定1->4->3->2->5->2 和 x =3 ,

返回1->2->2->4->3->5.

算法分析:

  * 分两次遍历单链表

  * 一次记录比目标值小的所有值

  * 一次记录比目标值大的所有值

  * 最终将这两个记录合并

  * 得到最终的结果

AC代码:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution 
{
    public ListNode partition(ListNode head, int x) 
    {
    	if(head==null) return head;
    	ListNode fhead = head;
    	ListNode shead = head;
    	ListNode res=new ListNode(0) ;
    	ListNode fres=res;
    	while(fhead!=null)
    	{
    		if(fhead.val<x)
    		{
    			res.next= new ListNode(fhead.val);
    			res=res.next;
    		}
    		fhead=fhead.next;
    	}
    	while(shead!=null)
    	{
    		if(shead.val>=x)
    		{
    			res.next= new ListNode(shead.val);
    			res=res.next;
    		}
			shead=shead.next;
    	}
    	return fres.next;
    }
}</span>


版权声明:本文为博主原创文章,转载注明出处

[LeetCode][Java] Partition List

原文:http://blog.csdn.net/evan123mg/article/details/46953903

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!