我一直在获取x,然后在Node中有一个私有访问。我试着玩,并不断得到相同的错误,无论我在我的节点类和我的链表类切换。我有我的节点保存在一个不同的文件,它看起来像这样:"
public class Node{
private Node next;
private String name;
private int ssn;
private int key;
public Node(String name, int ssn){
this.name = name;
this.ssn = ssn;
}
public void setNext(Node n){
this.next = next;
}
public int getSSN(){
return this.ssn;
}
public int getKey(){
return ssn%10000;
}
public String getName(){
return name;
}
public Node getNext(){
return this.next;
}
public void setSSN(int ssn){
this.ssn= ssn;
}
然后是我的链表堆栈代码就像这样:
public class StackLL{
private Node head; //Whatever is on top of the stack
private int n; //Suze of the stack
private Node next;
public StackLL(){
head = null;
n = 0;
}
public boolean isEmpty(){
return n == 0;
}
public void push(){
Node temp = head;
head = new Node();
head.x = x;
Node head.next = temp;
n++;
}
public Node pop(){
Node x = head.x;
head = head.next;
n--;
return x;
}
public Node top(){
return head.x;
}
// printStack method for StackLL
public void printStack() {
System.out.println(n);
Node temp = head;
while (temp != null) {
System.out.println(temp.getKey());
temp = temp.getNext();
}
}
}
我在你的代码中插入了关于我看到的问题的注释。在Node
类中只有一个,在setNext()
中:
public void setNext(Node n){
// assign the parameter to the field
this.next = n;
}
有一个数字在StackLL
类:
public class StackLL{
private Node head; //Whatever is on top of the stack
private int n; //Suze of the stack
// the field next is not used; just delete it
// private Node next;
public StackLL(){
head = null;
n = 0;
}
public boolean isEmpty(){
return n == 0;
}
public void push(){
Node temp = head;
// The Node constructor takes two arguments
head = new Node("Jim", 541365250);
// x is not defined; delete this statement
// head.x = x;
// Node.next is not visible (it’s private), so use the setter
head.setNext(temp);
n++;
}
public Node pop(){
// if you want to return a Node, just return head
Node x = head;
// next is private, use the getter
head = head.getNext();
n--;
return x;
}
public Node top(){
// if you want to return a Node, just return head
return head;
}
// printStack method for StackLL
public void printStack() {
System.out.println(n);
Node temp = head;
while (temp != null) {
System.out.println(temp.getKey());
temp = temp.getNext();
}
}
}
除了pop()
中的局部变量外,我没有发现x
,所以我删除或更改了对它的引用。返回仍然链接到其他节点的Node实例在生产代码中不是一个好主意,但我现在让它成为。