简体   繁体   English

链接列表从尾部删除

[英]Linked list removing from tail

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; 我试图从单个链接列表的末尾删除。我没有尾部变量来保持对列表中最后一项的引用。因此这是我的实现。我的问题是在while循环之后,如果我将current=null;设置为current=null; it doesn't work(It doesn't remove the last node).I have to set current.next=null; 它不起作用(它不会删除最后一个节点)。我必须设置current.next=null; .
But what do I have to add next for current.next=null; 但是,我有什么下一步添加current.next=null; .Even if I say current=null; 即使我说current = null; doesn't that mean point the node current to null.Can someone please explain why I have to use next there? 这并不意味着将当前节点指向null。有人可以解释一下为什么我必须在那里使用next吗?

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; 当您执行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; 您将(local)变量currentnull ,但是仍然在列表中指向同一对象,但您希望列表中的对象指向带有next成员( someobject.next )的最后一个对象,因此不再指向该对象,因此您需要更改someobject.next的值,例如someobject.next = null;

current is a reference to the current position in your linked list. current是对链接列表中当前位置的引用。 After the while loop, current refers to the second to last item. 在while循环之后, current是倒数第二个项目。 When you say current.next = null , you make the current object's next become null . 当您说current.next = null ,使当前对象的next成为null That makes the current object the last object. 这使当前对象成为最后一个对象。

When you say current = null , you are just setting your local reference variable to null . 当您说current = null ,您只是将本地引用变量设置为null In other words, it no longer refers to your list. 换句话说,它不再引用您的列表。 It refers to null . 它指的是null

Why not use remove method of List interface? 为什么不使用List接口的remove方法?

LinkedList<String> sss = new LinkedList<String>();
sss.add("a");
sss.add("b");
sss.remove(sss.size() - 1); // removes "b"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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