我正在编写一个代码,如果它们是唯一的,则将它们放在 MyStack 上。我不得不复制并粘贴节点起始代码,所以我遇到了一些问题。我不断收到两条错误消息,即使在尝试了各种解决方法之后,我也不太明白为什么。我什至尝试过使用我之前做过的一些辅助函数,所以我很困惑。我一直得到的两个错误是:
- 无法推断 MyStack.Node 的类型参数(实际参数和形式参数的长度不同) - 构造函数节点不能应用于给定类型。必需,无参数,找到:任何东西,
这是我的代码:
public class MyStack<Anything>
{
private Node first, last;
private class Node<Anything>
{
Anything item;
Node next;
}
public boolean contains(Anything value)
{
for (Node curr = first; curr != null; curr = curr.next)
{
if (value.equals(curr.item)) {
return true;
}
}
return false;
}
public void add(Anything value)
//method that adds a new value to the end of the list
//COMPLETE
{
Node temp = first;
while(temp.next!=null){ //finds the end
temp=temp.next;
}
temp.next=new Node(value, null); //assigns new value
}
public void enqueue(Anything info){
if (this.contains(info)==true) { //if the info is already present
System.out.println("the stack already contains this value");
return;
}
//if we actually need to add the info
if (first == null) { //if there is nothing in the stack
Node temp= first;
first = new Node<>(info,temp);
first = temp;
return;
}
if (first != null) { //if there is already stuff
Node temp = first;
while (temp.next == null)
{ Node newNode= new Node<>(info, temp);
temp.next = newNode;
}
return;
}
}
}