Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用节点类为堆栈类创建push()方法_Java_Stack - Fatal编程技术网

Java 使用节点类为堆栈类创建push()方法

Java 使用节点类为堆栈类创建push()方法,java,stack,Java,Stack,我在做一个赋值,我必须使用一个节点类创建我自己的堆栈类,我在做push()方法。这是我的密码: 对于类节点: class Node{ //attributes private String data; private Node next; //basic constructor Node(){ } Node(String data){ this.data = data; this.next = null

我在做一个赋值,我必须使用一个节点类创建我自己的堆栈类,我在做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;
    }
这是我到目前为止所采用的方法:

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。非常感谢在调试器中运行此命令,您将看到:

//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连接到堆栈中的所有其他节点

如果这回答了您的问题,请选中答案旁边的复选标记