/* related posts with thumb nails */

### Queue & different ways to implement a queue:

4 A queue is a linear data structure in which elements are added at the “rear” and deleted from the “front”.

4 A queue is a type of abstract data type that can be implemented as a linear list.

4 A queue has a front and a rear.

4 Insertion occurs at the rear of the list, and deletion occurs at the front of the list. This is called as “first-in-first-out” (FIFO) method.

Queue can be implemented mainly in two ways

1. Using arrays 2. Using Linked lists.

In both the ways, we need to write functions such as “qstore()” and “qdelete()” functions.

Program to implement insert and delete operations on Queue using array method.

class Queue

{

private static int MAX=10;

private int a[]=new int[MAX];

int front,rear;

Queue()

{

front=rear=0;

}

public void insert(int v)

{

if(rear

a[rear++]=v;

else

System.out.println("Overflow");

}

public int del()

{

if(front!=rear)

return a[front++];

else

{

System.out.println("Underflow");

return -1;

}

}

}

class QArray

{

public static void main(String as[])

{

Queue q1=new Queue();

q1.insert(30);

q1.insert(40);

q1.insert(50);

System.out.println(q1.del());

System.out.println(q1.del());

System.out.println(q1.del());

}

}

/* Output */

30

40

50

Program to implement insert and delete operations on Queue using linked list method

class node

{

public int x;

public node next;

}

class Queue

{

public node front,rear;

Queue()

{

front=rear=null;

}

void insert (int v)

{

node temp=new node();

temp.x=v;

temp.next=null;

if(front==null)

front=rear=temp;

else

{

rear.next=temp;

rear=temp;

}

}

int del()

{

int v=front.x;

node temp=front;

front=front.next;

temp=null;

return v;

}

}

class QueueList

{

public static void main(String as[])

{

Queue q1=new Queue();

q1.insert(30);

q1.insert(40);

q1.insert(50);

System.out.println(q1.del());

System.out.println(q1.del());

System.out.println(q1.del());

}

}

/* Output */

30

40

50

Related Topics: