简体   繁体   中英

LinkedList remove conditions (last iterated item)

I am attempting to remove the last iterated element, with a custom iterator/linked list class. It for some reason only does this for the first item in the list (the head condition). Is there anything wrong with the conditions?

Should I, instead of the Else after If (prev=head), write If (next != null) to find middle nodes, and If (next = null) to find the last node? Second question: to remove the items, should I also write prev.element = null (now I only have prev = null, and I suppose that erases the node but not its content.

Quite simply, what is wrong with my remove method, as I cannot figure it out myself. Thank you guys so much in advance. I have been working many hours with this but I still haven't got it working.

public E next() {
    if (!hasNext())
        throw new NoSuchElementException ();
    prev = next;
    E element = next.element;
    next = next.next;
    return element;
}

public void remove() { 
    if(prev == null) {
        throw new IllegalStateException();
    }
    else {
        if(prev == head){
            head = head.next;
            next = head;
        }
        else {
            next = prev.next;
        }
        sizeOfList--;
        prev = null;
    }
}

This is my best guess with the given code

if(prev == head){ should change to if(prev.equals(head)){ Use equals method.

And I think you have to override equals method in the corresponding element class might definitely help.

== only checks for whether both variables refer to same object in memory, where as equals check Object state .

I hope it helps :).

You would need a while loop to be able to go through every node in the list until you hit the last one. As it is now, your code simply goes past the head, and then gets into the code that says sizeOfList-- and then prev = null;

You need something like this:

while (prev.next.next != null) {
    prev = prev.next;
}

prev.next = null;

I do prev.next.next so that you can set the 2nd to last node in your linked list to point to a null value (which is done by prev.next = null; ). Think of it this way: prev is the 2nd to last element in the list, prev.next is the last element, and obviously prev.next.next HAS to be null (because prev.next is LAST.) So once this is the case, delete the last element by setting the 2nd to last element to point to a null value.

And then decrement your list count.

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