【问题标题】:Why is my basic stack code in java not running?为什么我在 java 中的基本堆栈代码没有运行?
【发布时间】:2021-05-11 01:04:42
【问题描述】:

所以我正在尝试编写堆栈数据结构的基础知识,当我在 sample_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);
    }           
}
    
}

提前谢谢你!

【问题讨论】:

    标签: java linked-list stack


    【解决方案1】:
    public void push(String itemName) {
        head = new Node(itemName, head);            // so head is the top of the stack ????
    }
    

    调用构造函数时head为null,因此此处的链接public Node(String item, Node link) {始终为null

    你不想,

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

    更重要的是,您应该在进行过程中调试所有这些

    【讨论】:

      猜你喜欢
      • 2014-05-18
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 2021-10-17
      • 2021-01-04
      相关资源
      最近更新 更多