代码之家  ›  专栏  ›  技术社区  ›  SomeoneLearning17

为什么java中的基本堆栈代码没有运行?

  •  0
  • SomeoneLearning17  · 技术社区  · 4 年前

    因此,我试图编写一个堆栈数据结构的基本代码,当我在sample\ u stack中运行这个类时,它只是不运行,不打印单词,而是只打印“null”:(有人知道为什么吗?如果这是显而易见的,我道歉

    堆栈JAVA类:

    import java.util.NoSuchElementException;
    public class Stack {
    
    // private inner class node
    
    private class Node{
        
        private String item;
        private Node link;
        
        public Node() {
            item = null;
            link = null;
        }
        
        public Node(String item, Node link) {
            item = this.item;
            link = this.link;
        }
        
    }  // end of inner class 
    
    private Node head;
    
    public Stack() {
        head = null;
    }
    
    // method: PUSH into stack          (like addToStart)
    
    public void push(String itemName) {
        head = new Node(itemName, head);            // so head is the top of the stack ????
    }
    
    // method: POP out of stack
    
    public String pop() {
        if (head == null) throw new IllegalStateException();
        
        else {
            String returnItem = head.item;
            head = head.link;   // the second top item becomes the new head
            return returnItem;
        }
    }
    
    // method: is it empty?
    
    public boolean isEmpty() {
        return ( head == null );
    }
    }
    

    使用堆栈JAVA类初始化:

    public class Stack_Example {
    
    public static void main (String[] args) {
        
        Stack message = new Stack();
        
        message.push("Hi");
        
        System.out.println(message.pop());
        
        message.push("my");
        message.push("name");
        message.push("is");
        message.push("JARVIS");
        
        
        while (!message.isEmpty()) {            // while true
            String s = message.pop();
            System.out.println(s);
        }           
    }
        
    }
    

    提前谢谢!

    1 回复  |  直到 4 年前
        1
  •  4
  •   Hovercraft Full Of Eels    4 年前
    public void push(String itemName) {
        head = new Node(itemName, head);            // so head is the top of the stack ????
    }
    

    当你调用构造函数时,head是空的,所以这里的链接, public Node(String item, Node link) { 始终为空

    你不想,

    public void push(String itemName) {
        head = new Node(itemName, this);
    }
    

    相反呢?

    而且,这是向后的:

    public Node(String item, Node link) {
        item = this.item;
        link = this.link;
    }
    

    应该是:

    public Node(String item, Node link) {
        this.item = item;
        this.link = link;
    }