简体   繁体   中英

Data structure in Java with operation remove all nodes after a node

I'm looking for a (predefined)data struture in Java, which will remove all the elements after a node. A sample representaion given below.

eg:

Before removal

head
 ┕>1 -> 2 -> 3 -> 4 -> 5 -> 6 ->7

After removal

removeAllFrom(5)

head
┕>1 -> 2 -> 3 -> 4

I checked a lot of java DS, but didn't find a perfect one in java.

(1 . Preferred a data structure which is in java.util.

2 . Insertion at head and iteration are the other operations which i'm using)

Thanks for the help :)


Edit - 1

After finding the element specified for removal(in the sample its 5), we just need to remove the links between the next node.

I checked the implementation of the answers given, but in both the cases it is removing each node separately. Just curious to know any other way to do it. :)

public void clear() {
    removeRange(0, size());
}

protected void removeRange(int fromIndex, int toIndex) {
    ListIterator<E> it = listIterator(fromIndex);
    for (int i=0, n=toIndex-fromIndex; i<n; i++) {
        it.next();
        it.remove();
    }
}

Well, java.util.LinkedList implements the List interface, which has a subList() method. Using that method, you can obtain a sub-list of the tail of the original list, and by clearing it, truncate the original List:

list.subList(firstIndexToRemove,list.size()).clear();

From the Javadoc:

List java.util.List.subList(int fromIndex, int toIndex)

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:

list.subList(from, to).clear();

This requires that you know the index of the node from which you want to remove all the elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM