我正在尝试编写用于删除链表中第k个元素的代码。我无法理解这里的错误是什么。如果我有人解释错误,我将非常感激。
/*
Write a method delete() that takes an int argument k and deletes the kth element in a linked list if it exists.
*/
class Deletenode
{
private int N;
private class Node
{
String item;
Node next;
}
// Building a Linked List
Deletenode()
{
Node first = new Node();
Node second = new Node();
Node third = new Node();
Node fourth = new Node();
Node fifth = new Node();
Node sixth = new Node();
first.item = "to";
second.item = "be";
third.item = "or";
fourth.item = "not";
fifth.item = "to";
sixth.item = "be";
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
fifth.next = sixth;
sixth.next = null;
}
public void delete(int k)
{
int i = 1;
for(Node x = first; x!= null || i== --k; x = x.next,i++)
{
if(i == k-1)
x = x.next.next;
}
}
public void show()
{
for(Node x = first; x!= null; x = x.next)
{
System.out.print(x.item);
}
}
public static void main(String[] args)
{
Deletenode d = new Deletenode();
d.show();
d.delete(3);
d.show();
}
}
我得到的错误是
deleteknode.java:44: error: cannot find symbol
for(Node x = first; x!= null || i== --k; x = x.next,i++)
^
symbol: variable first
location: class Deletenode
deleteknode.java:54: error: cannot find symbol
for(Node x = first; x!= null; x = x.next)
^
symbol: variable first
location: class Deletenode
2 errors
提前致谢
答案 0 :(得分:1)
你不能将这样的代码直接放在一个类的主体中。
first.item = "to";
second.item = "be";
third.item = "or";
fourth.item = "not";
fifth.item = "to";
sixth.item = "be";
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
fifth.next = sixth;
sixth.next = null;
将其移动到实例初始值设定项,构造函数或方法并调用它。
此外,您已为自己的班级Item
声明了一个类型参数。它是无界限的,因此您不能将String
值分配给使用该泛型类型声明的元素。
另外,这个
if(x == k-1)
没有意义,因为x
是Item
而k-1
解析为int
值。你不能比较这两者。您可能想要计算您已迭代的节点数。