Queue implementation using SinglyLinkedList

Program


package com.wordpress.sreeharshasite;
public class NodeG<T> {
int data;
NodeG<T> nextNode;
public NodeG(int data)
{
this.data=data;
this.nextNode=null;
}
}


package com.wordpress.sreeharshasite;
public class QueueLinkedList<T> {
NodeG<T> headNode=null;
int size=0;
NodeG<T> currNode=null;
public void add(int data)
{
currNode=headNode;
NodeG<T> newNode=new NodeG<T>(data);
/*if there are no nodes in the list add the new node to the headNode*/
if(currNode==null)
{
currNode=newNode;
headNode=currNode;
size++;
}
else
{
/*if there is only head node in the list add the new node next to the headNode*/
if(currNode.nextNode==null)
{
currNode.nextNode=newNode;
headNode=currNode;
size++;
}
/*add the new node at last in the list*/
else
{
NodeG<T> prevNode=null;
while(currNode!=null)
{
prevNode=currNode;
currNode=currNode.nextNode;
}
prevNode.nextNode=newNode;
size++;
}
}
}
public void delete()
{
currNode=headNode;
/*if no nodes to delete return*/
if(currNode==null)
{
return;
}
else
{
/*if only one nodes to delete , delete the headNode*/
if(currNode.nextNode==null)
{
currNode=null;
size--;
}
/*delete the first node in the list*/
else
{
currNode=currNode.nextNode;
headNode=currNode;
size--;
}
}
}
public void display()
{
currNode=headNode;
while(currNode!=null)
{
System.out.print(currNode.data+" ");
currNode=currNode.nextNode;
}
System.out.println();
}
}


package com.wordpress.sreeharshasite;
public class QueueLinkedListDemo {
public static void main(String[] args) {
QueueLinkedList<Integer> qll=new QueueLinkedList<Integer>();
qll.add(10);
qll.add(20);
qll.add(30);
qll.add(40);
qll.add(50);
System.out.println("After Insertion");
qll.display();
qll.add(570);
System.out.println("After Insertion");
qll.display();
qll.delete();
System.out.println("After Delete");
qll.display();
qll.delete();
System.out.println("After Delete");
qll.display();
}
}

Output

After Insertion
10 20 30 40 50 
After Insertion
10 20 30 40 50 570 
After Delete
20 30 40 50 570 
After Delete
30 40 50 570
Advertisements

I am Sreeharsha from Bengaluru. I am working in java for the past 6+ years. In this blog i will be sharing posts regarding java , advanced java , monthly challenges, collection of quotes , my themes and many more. If you like my posts please follow my blog.

Tagged with: , , ,
Posted in Core Java, Data Structures

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow My Diary on WordPress.com
Archives

Enter your email address to follow this blog and receive notifications of new posts by email.

%d bloggers like this: