我是java的初学者,因为它们的复杂性,我无法理解Java中的链表。所以我的代码非常简单。如何从循环链表中删除节点?
Node node, head, tail;
head = null; // initializes the head of the linked list to null
int counter = 0;
String inputdata; // input
do
{
System.out.print ("What name would you like stored? (\"quit\" to end) ");
inputdata = stdin.readLine();
if (!inputdata.equals ("quit"))
{
node = new Node (inputdata);
node.next = head;
// update the head to point to the new front of the list
head = node;
count++;
}
}
while (!inputdata.equals ("quit")); // loop continues until "quit" selected
System.out.println();
node = head;
///////////////////////////////
String delete;
boolean found;
System.out.println ("What node to delete?");
delete = stdin.readLine();
do
{
for (int i = 0 ; i <= count ; i++)
{
if (delete.equals (node.data))
{
found = true;
System.out.println ("It is found!");
}
}
}
while (found = false);
这是类
public class Node
{
Node next;
String data;
public Node (String data)
{
this.data = data;
}
}
我理解该算法是如何工作的。一个节点被搜索,当它被发现时,它指向节点之前的节点到搜索节点之后的节点。
每当我搜索节点我得到java.lang.nullpointer例外,基本上转化为我的代码是可怕的。
我需要帮助,因为无论何时我搜索如何做到这一点,我总是问自己“为什么放这个”或“什么是LS”或“为什么有多种方法,其中的变量n是多少”。
请告诉我我做错了什么,我需要做什么。
虽然这可能不是解决方案(当我们不知道哪一行出现异常时,不能轻易给出解决方案),但搜索的while循环只会迭代一次。 'while while(found = false);'相当于'found = false; (while)(找到);'。相反,你应该检查等价性:'while while(found == false);'。 – Vulcan
这看起来很简单。但是,当分配节点它看起来很棘手 –