题目:
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>