java - 复制单链表

标签 java data-structures linked-list nodes

[3, 5, 4, 2, 1] 我需要删除靠近尾部的节点,它应该像 [1, 2, 3, 5, 4] 有什么建议吗?

public void delete() {
    for(Node<T> current = getHead(); current != null; current = current.getNext()){

                System.out.println(temp.getValue());
                removeValue(temp.getValue());
            }
        }
    }
}

最佳答案

您根本不需要删除任何内容(我的意思是不需要调用removeValue)。只需将您遇到的值存储在一个集合中,如果该值已经在集合中,则重新链接您的列表。如果您无权使用库代码,请使用二叉搜索树实现您的集合,这将很容易且相当高效。

这就是我要做的,假设我有一个 Set 的实现:

public void makeUnique() {
    Set<T>  set      = new MySet<>();
    Node<T> current  = getHead();
    Node<T> previous = null;
    while (current != null) {
        // if current.getValue() is already in the set, we skip this node
        // (the add method of a set returns true iff the element was not 
        // already in the set and if not, adds it to the set)
        if (set.add(current.getValue()) { 
            // previous represents the last node that was actually inserted in the set.
            // All duplicate values encountered since then have been ignored so 
            // previous.setNext(current) re-links the list, removing those duplicates
            if (previous != null) {
                previous.setNext(current); 
                current.setPrevious(previous);
             }
            previous = current;
        }
        current = current.getNext();
    }
}

关于java - 复制单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26823759/

相关文章:

java - 需要了解一项 PMD 规则

java - 工具栏在 Android 4.X 设备上不可见

java - GSON 解析与 Retrofit 解析 Flickr JSON 响应

c - 如何获取字符串中的特定字符

python defaultdict 如何在不创建 key 的情况下检查嵌套 key 是否存在或是否为 []

java - 删除链表中所有出现的元素

c - 在链表末尾插入

java - 如何从 Web 服务方法返回多个属性

objective-c - 改变 CGRect(或任何结构)?

java - LinkedList与堆栈