【问题标题】:Creating push() method for Stack class with Node class使用 Node 类为 Stack 类创建 push() 方法
【发布时间】: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。非常感谢

【问题讨论】:

    标签: java stack


    【解决方案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,否则您将无法将 node 连接到堆栈中的所有其余节点

    【讨论】:

    • 如果这回答了您的问题,请检查答案旁边的复选标记
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2020-01-12
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多