In: Computer Science
IN JAVA LANGUAGE
Linked List-Based Queue Implementation
Implement Queue using a Linked List.
Instead of using an array, as the QueueLab did, here you will use a Linked List from your language's library. Implement all the methods of Stack : enqueue(), dequeue(), size(), printQueue(), etc, using calls to the linked list methods that correspond to the actions need. In the array implementation, you wrote code to manipulate the array. For this linked list implementation, methods already exist.
Before the underlying implementation of queue was array, now the underlying implementation of queue will be Linked list.
Solution:
I have done your code as stated to implement queue using a linked list.
I had attached all my source code and screenshots for your reference.
NOTE: Create all classes separately in a folder then execute the code.
Souce Code:
1. Node.java
public class Node {
public String dt;
public Node next;
public Node()
{
next = null;
dt = " ";
}
public Node(String d,Node n)
{
dt = d;
next = n;
}
public void setnext(Node n)
{
next = n;
}
public void setdt(String d)
{
dt = d;
}
public Node getnext()
{
return next;
}
public String getdt()
{
return dt;
}
}
Screenshot:
2. Queue.java
import java.util.NoSuchElementException;
public class Queue {
Node fr, rer;
public int size;
public Queue()
{
fr = null;
rer = null;
size = 0;
}
public int Size()
{
return size;
}
public void enqueue(String data)
{
Node nptr = new Node(data, null);
if (rer == null)
{
fr = nptr;
rer = nptr;
}
else
{
rer.setnext(nptr);
rer = rer.getnext();
}
size++ ;
}
public String dequeue()
{
Node ptr = fr;
fr = ptr.getnext();
if (fr == null)
rer = null;
size-- ;
String s = ptr.getdt();
return s;
}
public void printQueue()
{
System.out.print("\nQueue = ");
if (size == 0)
{
System.out.print("Empty\n");
return ;
}
Node ptr = fr;
while (ptr != rer.getnext())
{
System.out.print(ptr.getdt()+" ");
ptr = ptr.getnext();
}
System.out.println();
}
}
Screenshot:
3. Test.java
import java.util.Scanner;
public class Test{
public static void main(String[] args)
{
Scanner s = new
Scanner(System.in);
Queue l = new Queue();
char ch;
do
{
System.out.println("\nOperations");
System.out.println("1. Enqueue");
System.out.println("2. Dequeue");
System.out.println("3. Size");
System.out.println("4. Print Queue");
System.out.println("5. Exit\n");
System.out.println("Enter your choice: ");
int choice = s.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter element to insert");
l.enqueue(s.next());
break;
case 2 :
try
{
System.out.println("Dequeued Element: "+
l.dequeue());
}
catch (Exception e)
{
System.out.println("Error: "+ e.getMessage());
}
break;
case 3 :
System.out.println("Size is: "+
l.Size());
break;
case 4 :
l.printQueue();
break;
case 5:
return;
default :
System.out.println("Invalid Choice! ");
break;
}
System.out.println("\nWish to continue (y/n): ");
ch = s.next().charAt(0);
}while (ch == 'Y'|| ch == 'y');
}
}
Screenshots:
The code is working fine..
Output: