我创建了两个类,即 Node 和 LinkedList。该代码是可编译的,但它永远不会生成我存储在链接列表中的最后一个数据。
考虑这两个类
节点.java
public class Node {
private int id;
private String name;
private Node next;
public Node(int id, String name) {
this.id = id;
this.name = name;
}
public int getID() {
return id;
}
public String getName() {
return name;
}
public void setID(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(int id, String name, Node next) {
this.id = id;
this.name = name;
this.next = next;
}
}
链表.java
public class LinkedList {
private Node start;
public LinkedList() {
start = null;
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.create(2345,"Peter");
list.create(3001,"Mary");
list.create(4763,"John");
list.create(3863,"Johnny");
list.display();
}
public void create(int id, String name) {
if(start == null) {
start = new Node(id, name, start);
}
else {
Node temp = start;
while(temp.getNext() != null) {
temp = temp.getNext();
}
Node newNode = new Node(id, name, null);
temp.setNext(newNode);
}
}
public void display() {
if(start == null) {
System.out.println("\nThe list is empty!");
}
else {
Node temp = start;
while(temp.getNext() != null) {
System.out.println("ID : " + temp.getID() + " Name : " + temp.getName());
temp = temp.getNext();
}
}
}
public void delete(int id, String name) {
Node previous = start;
Node temp = start;
while(temp.getID() != id) {
if(temp.getNext() == null) {
System.out.println("\nElement "+ id + " not found !");
break;
}
while(temp.getName() != name) {
if(temp.getNext() == null) {
System.out.println("\nElement "+ name + " not found !");
break;
}
previous = temp;
temp = temp.getNext();
}
if(temp == start) {
start = start.getNext();
}
else {
previous.setNext(temp.getNext());
}
}
}
}
在这种情况下,程序将生成存储在列表中的所有内容,但不会生成最后一个。
换句话说,程序不显示以下行,而存储的前三个数据可以毫无问题地输出。
list.create(3863,"约翰尼");
我可以知道我的代码有什么问题吗?提前致谢!=)