Below is a class, ListNode2, with a method named Display that contains a while loop. My other class, Stack, creates a ListNode2 object LN2 then calls the Display method. (I apologize if I’m misusing Object Oriented Programming terminology.) For some reason, when I run them, the while loop gets stuck, I’m pretty sure at the condition. The output is “head3,” and the program keeps running, stuck in an infinite loop. After my Stack class, I’ve pasted a modified version of the Display method where the while loop uses a conditional with an int instead of a ListNode2. Now the output is
head3In while loopIn getItem-->1Just after while loopJust before displayhead3In while loopIn getItem-->100Just after while loop
The program is getting into the body of the while loop. Why isn’t it doing so with the original Display method? At the very end, I'm pasting my class StackMain.java that I use as for the main method.
Code:// ListNode2.java
class ListNode2
{
int data;
private Object item;
private ListNode2 next;
public ListNode2 (int n)
{
ListNode2 head = Create(n);
Display(head);
}
public ListNode2 (Object newItem)
{
item = newItem;
next = null;
}
public ListNode2 (Object newItem, ListNode2 nextNode)
{
item = newItem;//left most part of new head
next = nextNode;//the rest of the new ListNode2, and the entire previous head
}
public Object getItem()
{
System.out.print("In getItem\n");
return item;
}
public void setItem (Object newItem)
{
item = newItem;
}
public ListNode2 getNext()
{
return next;
}
public void setNext (ListNode2 nextNode)
{
next = nextNode;
}
public static ListNode2 Create (int n)// creates a linked list of length n, n>0, with data counting down from n to 1.
{
ListNode2 head = new ListNode2(n, null);
while (n>1)
{
n = n-1;
head = new ListNode2 (n, head);
}
return head;
}
public static void Display (ListNode2 head)
{
System.out.print ("head3");
while (head != null);
{
System.out.print ("In while loop");
System.out.print("-->" + head.getItem());
head = head.getNext();
}
System.out.print ("Just after while loop");
System.out.print("\n\n");
}
}
// Stack.java
// written by Aaron Poley
// Uses ListNode.
java import java.io.*;
class Stack
{
private ListNode2 LN;
private int size;
public Object itemObject = 100;
public Stack(int size)//constructor.
{
ListNode2 LN = new ListNode2(size);
ListNode2 LN2 = new ListNode2(itemObject, LN);
System.out.print ("Just before display");
LN2.Display(LN2);
}
}
//end Stack.java
public static void Display (ListNode2 head)
{
System.out.print ("head3");
// while (head != null);
int x1 = 1;
while (x1 != 0)
{
System.out.print ("In while loop");
System.out.print("-->" + head.getItem());
head = head.getNext();
x1 = x1-1;
}
System.out.print ("Just after while loop");
System.out.print("\n\n");
}
// StackMain.java
import java.io.*;
class StackMain
{
public static void main (String args[])
{
Stack Param = new Stack(5);
//ListNose2.Create(13)
// ??? Is there a way to call the Create method from outside the ListNode.java file?
}
}
