好吧,这只是一个简单的程序,它将接收用户的输入并将其添加到链接列表
中,并为他们提供查看列表
的选项并删除节点
。它编译得很好,可以添加节点并显示列表,但不会删除节点。当我在没有键盘输入的情况下手动编码时,即使变量名称相同,它也能工作,这就是问题所在。
public class LinkedList {
public class Link {
public String content;
public Link next;
public Link(String content) {
this.content = content;
}
public void display(){
System.out.println(content);
}
}
public static Link head;
LinkedList(){
head = null;
}
public boolean isEmpty() {
return(head == null);
}
public void insertFirstLink(String content) {
Link newLink = new Link(content);
newLink.next = head;
head = newLink;
}
public void display() {
Link theLink = head;
while(theLink != null) {
theLink.display();
theLink = theLink.next;
}
}
public Link removeLink(String content) {
Link curr = head;
Link prev = head;
while(curr.content != content) {
if (curr.next == null) {
return null;
}
else {
prev = curr;
curr = curr.next;
}
}
if(curr == head) {
head = head.next;
}
else {
prev.next = curr.next;
}
return curr;
}
}
public class Testlist {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int choice = 0;
String content;
System.out.println("Enter 1 to add to list");
System.out.println("Enter 2 to display list");
System.out.println("Enter 3 to delete node");
System.out.println("Enter 4 to quit");
choice = keyboard.nextInt();
LinkedList newlist = new LinkedList();
while(choice != 4) {
if (choice == 1) {
content = keyboard.next();
newlist.insertFirstLink(content);
newlist.display();
}
if (choice == 2) {
newlist.display();
}
if (choice == 3) {
content = keyboard.next(); // this is where is goes wrong
newlist.removeLink(content);
newlist.display();
}
System.out.println("Enter 1 to add to list");
System.out.println("Enter 2 to display list");
System.out.println("Enter 3 to delete node");
System.out.println("Enter 4 to quit");
choice = keyboard.nextInt();
}
}
}
最佳答案
您正在使用!=
,它通过对象的引用进行比较,而不是通过值进行比较。您想使用.equals()
,即:
while(!curr.content.equals(content))
关于Java - 从链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20438489/