最初想扫描一遍,把小的节点按照扫描的顺序一道前边。 后来发现完全不必如此。 我们可以用两个指针维护小于target的列表和大于等于target的列表。扫描一次将各节点按照顺序插入这些列表即可。 由于是指针,额外的空间消耗也是常数。 这种做法高效简单,避免了指针移动时可能会出现的各种错误。值得借鉴和思考。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if( head==null )
{
return head;
}
ListNode h1=null,c1=null;
ListNode h2=null,c2=null;
ListNode st=head;
while( st!=null )
{
if( st.val<x )
{
if( h1==null )
{
h1=st;
c1=st;
}
else
{
c1.next = st;
c1 = c1.next;
}
}
else
{
if( h2==null )
{
h2=st;
c2=st;
}
else
{
c2.next = st;
c2 = c2.next;
}
}
st=st.next;
}
if( c2!=null )
{
c2.next=null;
}
if( h1!=null )
{
c1.next=h2;
return h1;
}
else
{
return h2;
}
}
}
本文介绍了一种高效的链表分隔算法,通过使用两个指针分别维护小于目标值和大于等于目标值的节点列表,仅需一次遍历即可完成节点的重新组织。此方法避免了复杂的指针操作,降低了出错的可能性。
2816

被折叠的 条评论
为什么被折叠?



