86. Partition List
分区列表,给定⼀个数 x,比x小的在左边,其余在右边,且相对位置不能发⽣变化。
由于相对位置不能发⽣变化,所以不能⽤类似冒泡排序的思想。
int[] arr = new[] { 1, 4, 2, 3, 6, 5, 2 };
SLinkedList<int> slist = new SLinkedList<int>();
slist.AppendRange(arr);
Console.WriteLine("Before: " + slist.Print());
var rslt = slist.PartionList(4);
Console.WriteLine(" After: " + rslt.Print());
/// <summary>
/// 分区列表,小的在左边,大的在右边,位置相对不变
/// </summary>
/// <typeparam name="T">结点类型</typeparam>
/// <param name="source">单链表</param>
/// <param name="pivot">支点</param>
/// <returns></returns>
public static SLinkedList<T> PartionList<T>(this SLinkedList<T> source, T pivot) where T: IComparable<T>
{
// 构造2个新链表,遍历源链表,分别存储
if (source.IsEmpty())
{
return new SLinkedList<T>();
}
if (source.Head == null || source.Head.Next == null)
{
return source;
}
var tmp = new SLinkedList<T>(source);
var head = PartionList(tmp.Head, pivot);
tmp.Clear();
return new SLinkedList<T>(head);
}
private static SLinkedListNode<T> PartionList<T>(SLinkedListNode<T> head, T pivot) where T : IComparable<T>
{
SLinkedListNode<T> before = new SLinkedListNode<T>();
var beforeHead = before;
SLinkedListNode<T> after = new SLinkedListNode<T>();
var afterHead = after;
while (head != null)
{
if (head.Data.CompareTo( pivot) < 0)
{
before.Next = head;
before = before.Next;
}
else
{
after.Next = head;
after = after.Next;
}
head = head.Next;
}
after.Next = null;
before.Next = afterHead.Next;
return beforeHead.Next;
}