2.1编写代码,移除末排序链表中的重复结点。进阶,不使用缓冲区。

思路,直接访问整个链表,将每个结点加入散列表,若发现有重复元素,就将该结点从链表中移除,然后接着迭代。

//2.1编写代码,移除末排序链表中的重复结点。
public static void deleteDups(LinkedListNode n)
{
    Hashtable table = new Hashtable();
    LinkedListNode previous = null;
    while (n != null)
    {
        if (table.containsKey(n.data))
        {
            previous.next = n.next;
        }
        else
        {
            table.put(n.data, true);
            previous = n;
        }
        n = n.next;
    }
}

//2.1b不得使用缓冲区
public static void deleteDups(LinkedListNode head)
{
    if (head == null) return;
    
    LinkedListNode current = head;
    while (current != null)
    {
        LinkedListNode runner = current;
        while (runner.next != null)
        {
            if (runner.next.data == current.data)
            {
                runner.next = runner.next.next;
            }
            else
            {
                runner = runner.next;
            }
        }
        current = current.next;
    }
}

两者差不多,前者速度快,后者空间省。

原文地址:https://www.cnblogs.com/wuzhenyang/p/7756412.html