为什么我的基本堆栈代码在java不运行?



所以我试图编写堆栈数据结构的基础知识,当我在sample_stack中运行该类时,它根本不运行,也不打印单词,而只是打印"null"有人知道为什么吗?如果这是明显的道歉

STACK JAVA CLASS:

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

}

提前感谢!

public void push(String itemName) {
head = new Node(itemName, head);            // so head is the top of the stack ????
}

当你调用构造函数时头是空的,所以这里的链接,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;
}

更重要的是,您应该在执行

时调试所有这些。

相关内容

  • 没有找到相关文章

最新更新