In: Computer Science
Java Language:
Using program created in this lesson as a starting point, create a circular list with at least four nodes. A circular list is one where the last node is made to point to the first. Show that your list has a circular structure by printing its content using an iterative structure such as a while. This should cause your program to go into an infinite loop so you should include a conditional that limits the number of nodes to be printed to a specific value, for example 20.
Code:
class Node {
int value;
Node nextNode;
Node(int v, Node n)
{
value = v;
nextNode = n;
}
Node (int v)
{
this(v,null);
}
}
class Stack {
protected Node top;
Stack()
{
top = null;
}
boolean isEmpty()
{
return( top == null);
}
void push(int v)
{
Node tempPointer;
tempPointer = new Node(v);
tempPointer.nextNode = top;
top = tempPointer;
}
int pop()
{
int tempValue;
tempValue = top.value;
top = top.nextNode;
return tempValue;
}
void printStack()
{
Node aPointer = top;
String tempString = "";
while (aPointer != null)
{
tempString = tempString + aPointer.value + "\n";
aPointer = aPointer.nextNode;
System.out.println(tempString);
}
}
public class StackWithLinkedList{
public static void main(String[] args){
int popValue;
Stack myStack = new Stack();
myStack.push(5);
myStack.push(7);
myStack.push(9);
myStack.printStack();
popValue = myStack.pop();
popValue = myStack.pop();
myStack.printStack();
}
}
Node.java :
class Node {
int value;
Node nextNode;
Node (int v){
this.value=v;
}
}
-----------------------------
CLLOperations.java :
class CLLOperations{
Node head=null,tail=null;
//adding new node to CLL
public void addNewNode(int value){
Node newNode = new Node(value);
if(this.head==null){
this.head=newNode;
this.tail=newNode;
newNode.nextNode=head;
}else{
this.tail.nextNode=newNode;
this.tail= newNode;
this.tail.nextNode=head;
}
System.out.println("Node "+value+"is added succesfully");
}
//Displaying all nodes until count is 20 as per given question
public void display(){
Node current = this.head;
if(this.head==null){
System.out.println("list is empty");
}else{
for(int i=0;i<20;i++){
System.out.println(current.value);
current=current.nextNode;
}
}
}
}
-----------------------------
CircularLinkedList.java
public class CircularLinkedList{
public static void main(String[] args){
CLLOperations cll = new CLLOperations();
cll.addNewNode(10);
cll.addNewNode(15);
cll.addNewNode(11);
cll.addNewNode(21);
cll.display();
}
}
The output of the program is as below: