SLinkedList slist = new SLinkedList();
slist.AppendRange(new[] { 6, 1, 1, 2, 3, 3, 3, 4, 5, 5 });
Console.WriteLine("Before: " + slist.Print());
var rslt = slist.DeleteDuplicates();
Console.WriteLine(" After: " + rslt.Print());
///
/// 删除链表中重复的结点,只要是有重复过的结点,全部删除。
///
///
///
///
public static SLinkedList DeleteDuplicates(this SLinkedList source) where T : IComparable
{
if (source.IsEmpty())
{
return null;
}
if (source.Head == null || source.Head.Next == null)
{
return source;
}
var tmp = new SLinkedList(source);
var head = DeleteDuplicates(tmp.Head);
tmp.Clear();
return new SLinkedList(head);
}
private static SLinkedListNode DeleteDuplicates(SLinkedListNode head) where T : IComparable
{
if (head == null)
{
return null;
}
if (head.Next != null && head.IsEqualTo(head.Next))
{
while (head.Next != null && head.IsEqualTo(head.Next))
{
head = head.Next;
}
return DeleteDuplicates(head.Next);
}
head.Next = DeleteDuplicates(head.Next);
return head;
}