The psuedo-code our professor provided is as follows:
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;
}
}
When the professor wrote this psuedo-code (as a sketch), she either didn't explain it well or I just could not understand it (this is all she gave us for Stacks). For this reason, I am having trouble re-creating the code. I can make a Stack Data Structure using the push method due to looking it up on the internet, but the final is fill in the blank, so I'd like to make sure I understand how to do it her way. The following is my attempt:
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();
}
}
}
The Node Class:
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;
}
}
Unfortunately, the code only creates 2 Nodes when I put 3 as my user-input. I tried it by making the for loop just go to N, however, it didn't make a difference. What exactly is the problem?
I think I understand what your professor wants. You're code is almost correct. The only thing you did wrong is the content of the for loop. According to your professor it should be:
CurrentNode.setLink(Head);
Head = CurrentNode;
The only thing your professor didn't do in there is to create a new CurrentNode. So that code will translate as something like this using what you've done so far:
currentNode = new Node (randomGenerator.nextInt(100),null);
currentNode.setLink(head); //push
head = currentNode;
Other than that your code look fine.