在java实现单链表时,为什么没有打印链表的最后一个元素?

In java implementation of Singly Linked List, Why is the last element of the linked list not being printed?

public class Linked_List <E>{
    public static class Node<E>{
        private E element;
        private Node<E> next;
        public Node(E e,Node<E> n) {
        element=e;
        next=n;
    }
    public E getElement() {
        return element;
    }
    public Node<E> getNext() {
        return next;
    }
    public void setNext(Node<E> n) {
        next=n;
    }
}

public Node<E> head=null;
public Node<E> tail=null;
public int size=0;

public Linked_List() {}

public int size() {
    return size;
}

public boolean isEmpty() {
    return size==0;
}
public void addFirst(E e) {
    head=new Node<>(e,head);
    if(size==0)
        head=tail;
    size++;
}

public void addLast(E e) {
    Node<E> newest =new Node<>(e,null);
    if(isEmpty())
        head=newest;
    else
        tail.setNext(newest);
    tail=newest;
    size++;
}
public void show() {

    Node<E> n=head;
    if(size==0) {
        System.out.println("No elements to print");
        System.exit(0);
    }
    while(n.next!=null) {
        System.out.println(n.element);
        n=n.next;
    }
    System.out.println(n.element);
}

public static void main(String[] args) {
    Linked_List<Integer> list = new Linked_List<Integer>();

    list.addFirst(10);
    list.addFirst(11);
    list.addFirst(12);

    list.show();

}
}

在 show() 方法中,当 while 到达列表的最后一个元素时,它会退出,因此不会打印该元素。因此,显示方法中的最后一个打印语句。 我已将三个元素添加到列表中,但是当我执行 show() 方法时,仅打印前两个元素 12 和 11。我错过了什么?谢谢

这里呢。这应该说 tail = head;

    public void addFirst(E e) {
        head = new Node<>(e, head);
        if (size == 0) {
            head = tail;
        }
        size++;
    }

问题出在while循环条件:

while(n.next!=null) {
        System.out.println(n.element);
        n=n.next;
    }

当列表到达元素 n-1 时,它将打印该元素,然后 n 将变为 n=n.next,这是最后一个元素。但是现在 n 是最后一个元素,他的 n.next 将为空,因此 while 将中断,因为不再满足条件。

您回答了自己的问题:

In show() method when the while reaches the last element of the list, it exits so the element doesn't get printed.

此代码:

while(n.next!=null) {
    System.out.println(n.element);
    n=n.next;
}

说 "while it's not the last element, print it"。即,代码明确不想打印最后一个元素。

我在这里假设您没有在问题描述中包含最终打印语句 - 您添加了最终打印语句来解决 while 循环问题。

你需要:

while (n != null) {
    System.out.println(n.element);
    n = n.next;
}

表示 'while it is an actual element, print it'。

addFisrt() 更改为:

public void addFirst(E e) {
    head = new Node<>(e, head);
    size++;
}

您可以调试 addFirst(),第一个元素永远不会添加到 LinkedList。