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;}
}
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
, eg someobject.next = null;
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
.
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"
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.