duplicate the singly linked list

五迷三道 提交于 2019-12-25 15:01:46

问题


[3, 5, 4, 2, 1] where I need the delete the nodes close to the tail which is it should be like [1, 2, 3, 5, 4] any suggestions?

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

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

回答1:


You don't need to remove anything at all (I mean not by calling removeValue). Just store the values you encounter in a set and if the value is already in the set, re-link your list in consequence. If you don't have the right to use library code, implement your set with a binary search tree, it will be easy and quite efficient.

This is how I would do, assuming I have an implementation of 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();
    }
}


来源:https://stackoverflow.com/questions/26823759/duplicate-the-singly-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!