简体   繁体   中英

Creating a sorted linked list class

I'm trying to create a SortedLinkedList class which extends LinkedList. This class is supposed to add items to a SortedLinkedList and have them sorted.

I'm trying to override the boolean add(E obj) method in order to add items in sorted order.

On a Stackoverflow question I found the following method of overriding add(E obj):

public boolean add(E obj) {
    int index = 0;
    for( ; index<size() ; index++){
        E object= get(index);

        if(obj.compareTo(object) < 0){
            break;
        }
    }

    add(index, obj);
    return true;
};

I understand how this method works, however I've read that using a ListIterator would be more efficient than using get(index). I've been trying to use a ListIterator but I can't seem to get everything to work correctly.

This is how far I got with using the Listiterator, I'm sure there is something wrong with it but I can't seem to figure it out:

public boolean add(E obj)
{   
    add(size(), obj);
    ListIterator<E> iterator = listIterator();

    while(iterator.hasNext())
    {
        E object = iterator.next();
        if(obj.compareTo(object)<0)
        {
            //do something;
        }
    }
    return true;
}

Any advice on how I can sort the list using the iterator?

Don't think about sorting the list using the iterator. Think about inserting a new element into an already-sorted list using the iterator.

Your list will start off empty. When you add the first element, you will have a list of one element, which is, by definition, sorted. If you make sure that you always add subsequent elements in the right place, then the list will stay sorted!

This is exactly what the code that uses get does, but as you quite rightly say, that is not efficient for linked lists. What you need to do is reproduce that algorithm using the iterator.

Hint: a list iterator lets you add an element at the current position .

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