[英]Push method for Stack with Nodes
我在做涉及 Java 中的堆栈和节点的家庭作业时遇到了麻烦。 我了解堆栈的概念,但对节点感到困惑。 任务是使用堆栈(不是 java.util.Stack)编写一个程序,该程序检查数学表达式中正确的 ()、[] 和 {} 对。 我们已经有了 Node 程序。 所以基本上我的问题是我想要一些帮助来完成我的 PStack class 的推送方法。
class PStack {
private Node top;
public PStack() {
top=null;
}
public boolean isEmpty() {
return top==null;
}
public int pop() {
Node top1 = top;
top = top.getNext();
return top1.getData();
}
public void push(Node n) {
}
public int peek() {
return top.getData();
}
}
public class Node {
private int data;
private Node nextnode;
public Node(int intial) {
data = intial;
nextnode = null;
}
public int getData() {
return data;
}
public Node getNext() {
return nextnode;
}
public void setData(int newdata) {
data = newdata;
}
public void setNode(Node next1node) {
nextnode = next1node;
}
}
我试过了:
public void push(Node n) {
Node next = n;
top.getNext().setNode(n);
}
结果:
Exception in thread "main" java.lang.NullPointerException
at javaclass.stack.pStack.push(pStack.java:24)
at javaclass.stack.StackDriver.main(StackDriver.java:17)
public void push(Node n) {
n.setNode(top);
top = n;
}
编辑:
顺便说一句,这是一个奇怪的堆栈实现。 看起来它想成为一堆 int 原语。 peek() 和 pop() 都返回一个 int。 但是 push 需要一个参数,该参数应该是堆栈本身的内部构造。 它不应该将节点 object 作为参数。 它应该接受一个 int 参数并在内部用 Node object 包装它。
此外,Node.setNode 应该命名为 Node.setNext。 它与您正在做的事情更加一致。 链表节点具有“下一个”成员,双链表节点具有“下一个”和“上一个”成员。 节点 object 的 getter 和 setter 应该为这些成员适当命名。
像这样:
PStack.java
public class PStack {
private Node top;
public boolean isEmpty() {
return top==null;
}
public int pop() {
Node top1 = top;
top = top.getNext();
return top1.getData();
}
public void push(int data) {
Node newtop = new Node(data);
newtop.setNext(top);
top = newtop;
}
public int peek() {
return top.getData();
}
}
节点.java
public class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.