我在喜欢列表中添加元素时遇到问题
public class LinkedList {
public Node first;
public Node last;
public LinkedList() {
first = null;
last = null;
}
public void addFirst(Student student) {
Node f = first;
Node newNode = new Node(student);
first = newNode;
if (f == null) last = newNode;
else f.previous = newNode;
}
public void addLast(Student student) {
Node l = last;
Node newNode = new Node(student);
last = newNode;
if (l == null) first = newNode;
else {
l.next = newNode;
}
}
public void display() {
Node current = first;
while (current != null) {
//print...
current = current.next;
}
}
我的问题是当我运行时:
list.addLast(1);
list.addFirst(2);
list.display();
它只显示“2”“显示”方法,只是看不到最后添加的元素。
但是如果我运行:
list.addFirst(2);
list.addLast(1);
它将显示两者。它有什么问题?谢谢。