Program : Queue Using Linked List
import java.io.*; //To implement I/O operations
class Link
{
int data; //data item
Link next; //next link in list
Link(int d) //constructor
{
data=d; //initialize data
}
void displayLink() //To display the list
{
System.out.print(" "+data);
}
} //end of class link
class list
{
Link first; //ref to first link on list
Link last; //ref to last link on list
list() //constructor
{
first=null; //no links on list yet
last=null; //no links on list yet
}
void insert(int d) //To insert into the list
{
Link l=new Link(d); //make new link
if (first==null) //to check if queue is empty
{
first=l;
last=l;
}
else
{
last.next=l;
last=l;
}
} //End of function insert
void delete() //To delete node from the list
{
if (first==null) //Check if queue is empty
{
System.out.println("Queue is empty:");
//Print queue Empty
}
else
{
first=first.next;
}
} //End of function delete
void display() //To display the queue
{
Link current=first; //start at the beginning of the list
while (current!=null) //until end of the list
{
current.displayLink(); //print data
current=current.next; //move to next link
}
System.out.println(" ");
} //end of function display
} //End of class list
public class Queuelink //The main class LinkQueue
{
public static void main(String args[]) throws IOException
//Main function
{
list q=new list(); //make new linklist
int d,c=0;
char f;
do
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\t\t\nQueue Operations");
//Print Menu
System.out.println("\n1.Push into Queue");
System.out.println("\n2.POP from Queue");
System.out.println("\n3.Display Queue\n");
System.out.print("Enter your Choice:");
c=Integer.parseInt(in.readLine());
//Accepts choice
switch (c)
{
case 1:
{
int p,flag=0;
{
System.out.println("Enter number of elements:");
d=Integer.parseInt(in.readLine());
while (flag<d)
{
System.out.println("Enter Element:");
p=Integer.parseInt(in.readLine());
q.insert(p);
//Assign values to links
flag++;
}
}
break;
}
case 2:
{
q.delete(); //Call the function delete
break;
}
case 3:
{
System.out.println("CURRENT LIST IS:");
q.display(); //Call the function display
break;
}
}
System.out.print("DO YOU WANT TO CONTINUE(y/n):");
f=(char)in.read();
}
while((f=='y')||(f=='Y'));
}
} //End of main function
0 comments:
Post a Comment