我们教授提供的伪代码如下:
Node Head;
int N; //(# of nodes in the stack)
if (N > 0) {
Head = CurrentNode //She never creates a current node?
for (int x = 0; x < (n-1); x++) { //I don't understand the n-1.
CurrentNode.setLink(Head);
Head = CurrentNode;
} else {
System.out.println("No Stack Possible");
} if (N == 0) {
Head = Null;
}
}
当教授写下这个伪代码(作为草图)时,她要么没有很好地解释它,要么我就是无法理解它(这是她为我们提供的 Stacks 的全部内容)。因此,我在重新创建代码时遇到了麻烦。由于在互联网上查找,我可以使用推送方法制作堆栈数据结构,但最终是填空,所以我想确保我了解如何按照她的方式去做。以下是我的尝试:
import java.util.Scanner;
import java.util.Random;
public class Stack
{
public static void main(String[] args) {
Node head= null;
head = generateStack();
Print(head);
}
public static Node generateStack() {
Random randomGenerator = new Random();
Node head = new Node (randomGenerator.nextInt(100),null);
Node currentNode = head;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the amount of Nodes you would
like to enter.");
int N = input.nextInt();
Node newNode = null;
if (N > 0) {
for (int i = 0; i < (N-1); i++) {
newNode = new Node (randomGenerator.nextInt(100),null)
currentNode.setLink(newNode); //push
head = currentNode;
}
} else {
System.out.println("No Stack Possible!");
}
if (N==0) {
head = null;
} return head;
}
public static void Print(Node entry)
{
Node Current = entry;
while (Current != null){
System.out.print(Current.getData() + " -> ");
Current = Current.getLink();
}
}
}
节点类:
public class Node
{
private int data;
private Node link
public Node(int ndata, Node nlink)
{
data = ndata;
link = nlink;
}
public int getData(){
return data;
}
public Node getLink(){
return link;
}
public void setData(int mydata){
data = mydata;
}
public void setLink(Node mylink){
link = mylink;
}
}
不幸的是,当我将 3 个节点作为用户输入时,代码仅创建 2 个节点。我尝试让 for 循环只转到 N,但是,这没有什么区别。到底是什么问题呢?
最佳答案
我想我明白你的教授想要什么。你的代码几乎是正确的。你唯一做错的就是 for 循环的内容。根据你的教授的说法应该是:
CurrentNode.setLink(Head);
Head = CurrentNode;
你的教授唯一没有做的就是创建一个新的 CurrentNode。因此,使用您到目前为止所做的代码将被转换为类似这样的内容:
currentNode = new Node (randomGenerator.nextInt(100),null);
currentNode.setLink(head); //push
head = currentNode;
除此之外,您的代码看起来不错。
关于java - 使用 For 循环手动创建堆栈的困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687150/