Frage

I am trying to remove at the end from a singly Linked List.I don't have a tail variable which keeps reference to the last item on the list..Therefore this is my implementation.My question is after while loop if I set current=null; it doesn't work(It doesn't remove the last node).I have to set current.next=null;.
But what do I have to add next for current.next=null;.Even if I say current=null; doesn't that mean point the node current to null.Can someone please explain why I have to use next there?

public void removeFromTail() throws EmptyStackException{
        if(head==null){
            throw new EmptyStackException("can't delete .Empty list");}
        else if(head.next==null){
            head=null;
        }
        else{
            ListNode current=head;
            while(current.next.next!=null){
                current=current.next;
            }


        current.next=null;}
}
War es hilfreich?

Lösung

current is a reference to the current position in your linked list. After the while loop, current refers to the second to last item. When you say current.next = null, you make the current object's next become null. That makes the current object the last object.

When you say current = null, you are just setting your local reference variable to null. In other words, it no longer refers to your list. It refers to null.

Andere Tipps

When you do current=null; you set the (local) variable current to null, but still the same object is pointed in your list, you want the object in the list which points to the last object with his next member (someobject.next) to stop pointing there, so you need to change the value of someobject.next, e.g. someobject.next = null;

Why not use remove method of List interface?

LinkedList<String> sss = new LinkedList<String>();
sss.add("a");
sss.add("b");
sss.remove(sss.size() - 1); // removes "b"
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top