【发布时间】: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