82. Remove Duplicates from Sorted List II
作者:互联网
SLinkedList<int> slist = new SLinkedList<int>();
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());
/// <summary>
/// 删除链表中重复的结点,只要是有重复过的结点,全部删除。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static SLinkedList<T> DeleteDuplicates<T>(this SLinkedList<T> source) where T : IComparable<T>
{
if (source.IsEmpty())
{
return null;
}
if (source.Head == null || source.Head.Next == null)
{
return source;
}
var head = DeleteDuplicates(source.Head);
return new SLinkedList<T>(head);
}
private static SLinkedListNode<T> DeleteDuplicates<T>(SLinkedListNode<T> head) where T : IComparable<T>
{
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;
}
标签:head,return,Duplicates,List,Remove,Next,source,null,DeleteDuplicates 来源: https://www.cnblogs.com/wesson2019-blog/p/15870200.html