【发布时间】:2020-11-11 02:41:18
【问题描述】:
我正在执行一项任务,我必须使用 Node 类创建自己的 Stack 类,我正在执行 push() 方法。这是我的代码:
对于类节点:
class Node{
//attributes
private String data;
private Node next;
//basic constructor
Node(){
}
Node(String data){
this.data = data;
this.next = null;
}
//accessors
public String getData(){
return this.data;
}
public Node getNext(){
return this.next;
}
//mutators
public void setData(String tmpData){
this.data = tmpData;
}
public void setNext(Node tmpNext){
this.next = tmpNext;
}
这是我目前做的方法push:
class MyStack{
//attributes
private Node top;
//constructor
MyStack(){
this.top = null;
}
//method to push a node into the stack
public void push(Node node){
Node next = node.getNext();
next = this.top;
this.top = node;
}
public void print() {
// Check if it's empty
if (this.top == null) {
System.out.println("Stack is empty.");
} else {
Node tmp = this.top;
while(tmp != null) {
System.out.print(tmp.getData()+ " ");
tmp = tmp.next;
}
System.out.println();
}
}
}
我用于测试的主要类:
class Main{
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(new Node("1"));
stack.push(new Node("2"));
stack.push(new Node("3"));
stack.print();
}
}
你们可以看看我的推送方法,因为当我打印时,我得到的唯一值是 3,我希望输出是 3 2 1。非常感谢
【问题讨论】: