使用 Node class 为 Stack class 创建 push() 方法

Creating push() method for Stack class with Node class

我正在做一个作业,我必须使用节点 class 创建自己的堆栈 class,我正在做 push() 方法。这是我的代码:

对于class节点:

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:

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();
        }
    }

你们能看看我的push方法吗,因为我打印的时候,我得到的值只有3,我希望输出是3 2 1。非常感谢

运行 这在调试器中,你会看到:

//method to push a node into the stack
public void push(Node node){
    Node next = node.getNext(); //If node is a new node, next is going to be null 
    next = this.top; // here you are just setting the variable you declared about to this.top. This erases setting next to node.getNext()
    this.top = node; // here you are setting this.top to node. You need to first set node.next = top
}

你想要的是:

//method to push a node into the stack
public void push(Node node){
    node.setNext(this.top);
    this.top = node; // now node is the top, and node.next is the previous top
}

确保首先设置 node.next,否则您将无法将节点连接到堆栈中的所有其余节点