java - 实现删除链表最后一个节点的方法

标签 java data-structures linked-list

我正在尝试删除 LinkedList 中的最后一个节点。 对于输入:1,2,3 输出应该是:1, 2

我可以删除节点,但是有更好/更有效的方法吗?

请检查removeLastNode()方法。

public class MyLinkedList {

Node head;
Node tail;

public void add(int number){

    Node node=new Node();
    node.setNumber(number);

    if(head==null){
        head=node;
        tail=node;  
    }
    else{
        tail.next=node;
        tail=node;          
    }

}



public void removeLastNode(){   
    Node temp=head;
    Node head1=null;
    Node tail1=null;


    while(temp.next!=null){

        Node node=new Node();
        node.number=temp.number;
        if(head1==null){
            head1=node;
            tail1=node; 
        }
        else{
            tail1.next=node;
            tail1=node;         
        }
        if(temp.next.next==null){               
            temp.next=null;
            break;
        }

        temp=temp.next;

    }
    head=head1;


}


@Override
public String toString(){
    while(head!=null){
        System.out.print(head.getNumber()+" ");
        head=head.getNext();
    }
    return "";
}

public static void main(String ar[]){

    MyLinkedList list=new MyLinkedList();
    list.add(1);
    list.add(2);
    list.add(3);
    list.removeLastNode();

    System.out.println(list);
}




public class Node{

    Node next;
    int number;
    public Node getNext() {
        return next;
    }
    public void setNext(Node next) {
        this.next = next;
    }
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }


}

}

最佳答案

使用tail作为最后一个节点。

public void removeLastNode() {
    if (head == null) {
        throw new IllegalStateException();
    }
    if (head == tail) {
        head = null;
        tail = null;
    } else {
        Node current = head;
        while (current.next != tail) {
            current = current.next;
        }
        current.next = null;
        tail = current;
    }
}

关于java - 实现删除链表最后一个节点的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38371684/

相关文章:

java - 黑客使 ReflectionFactory 工作(重新打包)

vb.net - 如何在 VB.NET 中为 List 中的结构元素赋值?

javascript - Array(0) 和 array = [] 有什么区别

c++ - 我们可以使用继承来实现链表吗?

python - Nonetype 在链表中没有属性 'next'

c - 当我想打印链接列表值时它发生了变化

java - MIDI 音序器停止而不冲洗

java - 获取@ClassbBridge字段值

java - Elasticsearch 前缀过滤器

java - 使用比较器接口(interface)时出错