83. Remove Duplicates from Sorted List

删除链表中重复的结点,以保障每个结点只出现⼀次。

int[] arr = new[] { 6, 1, 1, 2, 3, 3, 3, 4, 5, 5 };
SLinkedList<int> slist = new SLinkedList<int>();
slist.AppendRange(arr);
Console.WriteLine("Before: " + slist.Print());
var rslt = slist.DistinctDuplicates();
Console.WriteLine(" After: " + rslt.Print());

/// <summary>
/// 删除链表中重复的结点,每个结点只出现一次。
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static SLinkedList<T> DistinctDuplicates<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 tmp = new SLinkedList<T>(source);
    var head = DistinctDuplicates(tmp.Head);
    tmp.Clear();
    return new SLinkedList<T>(head);
}
private static SLinkedListNode<T> DistinctDuplicates<T>(SLinkedListNode<T> head) where T : IComparable<T>
{
    if (head == null || head.Next == null)
    {
        return head;
    }
    var cur = head;
    while (cur.Next != null)
    {
        if (cur.IsEqualTo(cur.Next))
        {
            cur.Next = cur.Next.Next;
        }
        else
        {
            cur = cur.Next;
        }
    }
    return head;
}
posted @ 2022-02-08 10:18  wesson2019  阅读(15)  评论(0编辑  收藏  举报