UNIT - II (Stacks and Queues)
UNIT - II (Stacks and Queues)
Sc
Stack:
A stack is an ordered collection of items into which new items may be inserted
and from which items may be deleted at one end, called the top of the Stack. Stack is a
memory which works with the concept (LIFO) “last in first out”.
Special terminology is used for two basic operations associated with stacks.
The removal or addition of elements can take place only at the top of the stack.
Top 10
8
6
4
2
Consider the above stack containing integers.
If an element is added to the stack, it will be placed on the top of 10. If a element
is to be deleted. It will be 10.
Ex:
push(12) on the stack push(14) on the stack
PUSH(16) on
POP an element POP an element
the stack
from the stack from stack
Top 12 Top 14 Top
10 12 16
top 12 Top 10
8 10
10 8 10
6 8 8
8 6
4 6
6 4 6
2 4
4 2 4
2 2 2
The last element pushed on to a stack is always the first that will be popped from the
stack that is why stack is called Last-In-First-Out (or) LIFO list.
Applications of Stack:
1. implementation of recursion
2. implement quick sort
3. converting infix expression to postfix expression
4. evaluation of postfix expressions
Implementation of Stacks:
There are two ways for implementing stacks. One is using arrays and other is
used by linked lists.
Operations on Stacks:
Associated with the stack, there are several primitive operations like creating
stack, pushing an element in to the stack, popping an element from the stack and
checking the stack, whether the stack is empty or not etc.,
If a stack is empty and it contains no elements, it is not possible to pop the stack.
Therefore before popping an element, one must ensure that stack is not empty. If stack
is implemented using linked lists there is no upper limit on the number of items that
may be kept in a stack except the limitations of the memory.
If stack is implemented using arrays, array size is the upper limit for the number
of items that may be kept in a stack.
Although an array can’t be a stack, it can be the home of the stack. We can
declare an array large enough so that the stack can grow and shrink with in the space
allotted for it during program execution. We can fix one end of the array as a bottom of
the stack, the other end of the array may be used as a top of the stack, which keeps
shifting constantly as items are popped and pushed.
Inserting or pushing an element into the stack:
ii) If stack is not full, increment the stack top so that it point to the next
location in the stack .
iii) Push the element into stack.
i) pushing is possible
(since top!=max-1)
1) Check whether the stack is empty or not. If stack is empty, we can’t pop an
element.
2) If stack is not empty pop the element form the stack pointed by the top.
3) Decrement stack top by one.
6
top element=40
5 top=3
max=7
4 max is the size of the array
Top 40 3
30 2
20
1
10
0
6
5
4
Top 30 3
2
20
1
10 0
The method of writing all operators either before their operands or after them is
called Polish notation. In general simple arithmetic expression can be represented in
three ways, Infix, Prefix, Postfix. In Infix notation the operator is placed between the
two operands. In Prefix notation, the operator precedes the two operands and in
postfix notation the operator follows the two operands.
Stack list can be maintained dynamically by using the concept of linked list.
Figure below shows the concept of stack implementation using linked list.
top
50 top element in stack
40
30
20
Where top is a pointer variable, which points to top element in the stack.
A new element can be pushed on to the stack by adjusting the pointers such that
top points to newly pushed element into the stack as shown in figure below.
50
40
30
20
60
Popped element
50 top element after popping
40
30
20
To display the elements of a stack, make sure that there are elements in the stack
if elements are available display them either top to bottom or bottom to top.
Creation of stack using linked list:
1. Create the first element. Hold the address of the first element in a separate
varible.
Ex: top
top
10 Null
2. push a new element when ever required by making ‘top’ points to new
element as shown below.
Ex: top
20 .
10 Null
30
20 .
10 NULL
4. to pop element, remove the element from top and make top points to next
element.
Ex: top
20
NULL
QUEUES
Queues are called fist-in-first-out (FIFO) lists, since the first element in a queue
will be the first element out of the queue.
10 20 30
Front Rear
‘30’ is the recently entered element into the queue. ‘10’ is the first element in the
queue. If an element is to be inserted into queue, it should be inserted after ‘30’. If an
element is to be deleted it should be 10.
Ex: insert(40)
10 20 30 40
Front Rear
20 30 40
Front Rear
Implementation of Queues:
Associated with the queue, there are several primitive operations like creating
queue, inserting an element into the queue, deleting an element from the queue,
displaying the contents of the queue etc.
If a queue is empty and it contains no element, it is not possible to delete an
element from the queue. Therefore, before deleting an element, we must ensure that
queue is not empty.
If queue is implemented using the linked list, there is no upper limit on the
number of elements that may be kept in a queue except the limitations of the memory.
If the queue is implemented using arrays, the no. of elements that can be kept in queue
is equal to the array size.
Array can be used to implement queue. Fig. below shows the concept of queue
implementation using array.
10 20 30 40
Front Rear
Where Rear is position from which insertion into queue is made. Front is
position from which deletion of elements is made. Front holds the index of the element,
which can be deleted next. Rear holds the index of the recently entered element into the
queue.
(i) Inserting an element into Queue: To insert an element
1. Check whether queue is full (or) not. If queue is full, we can’t insert an element.
2. If queue is not full increment the ‘rear’ by one, so that it points to the next
location in the queue.
3. Insert the element into queue.
Ex: Insert(40)
0 1 2 3 4
10 20 30
front=0
rear=2
front rear rear =2
i) Insertion possible since rear != max-1, where max is size of array.
ii) Increment is rear by one. rear = rear + 1
= 2+1
= 3
iii) Insert the element.
Queue after insertion:
0 1 2 3 4 front=0
10 20 30 40
rear=3
front rear
1. Check whether the queue is empty (or) not. If queue is empty, we can’t delete an
element.
2. If it is not empty, delete the element from queue, which pointed by the ‘front’ of
the queue.
3. Increment the ‘front’ by one.
0 1 2 3 4 Front=3
a
40 50
Rear=4
Front Rear
Insertion of another element into above queue is not possible, because the array
can accommodate only 5 elements and last element will be placed at a[4]. Even though,
there is space at a[0], a[1], a[2] the element can’t be inserted.
The inefficient use of space can be overcome by simply viewing the array as a
circular rather than a straight line as shown in fig. below.
0 1 2 3 4
40 50
3 1
2
In a circular queue after inserting an element at last position, the next element
will be inserted at first position, if ‘front’ of the queue is not at first position.
Ex: Consider the following circular queue.
0 1 2 3 4 5 Array Index
30 40 50
front rear
0 1 2 3 4 5
60 30 40 50
rear front
0 1 2 3 4 5
60 40 50
rear front
Operations on Circular Queues : The following operations can be performed on circular
queues. Implementation, insertion, deletion and display the elements.
Inserting an element into circular queue : To insert an element into circular queue
If rear is at the maximum position and front is not at first position, update the rear
so that, it points to first position, otherwise increment the rear.
0 1 2 3 4
20 30 40
front rear
Insert 50 : Queue will be
0 1 2 3 4
20 30 40 50
front rear
Insert 60 : Queue will be
0 1 2 3 4
60 20 30 40 50
rear front
Deleting an element from Circular Queue : To delete an element from the Circular
Queue.
1. Check whether there are elements in queue to delete.
2. If there are elements, delete the element from the front position.
3. Update the front. If front is at maximum position and rear is not at minimum
position.
4. Update the front so that, it points to minimum position otherwise increment the
front.
Ex: Consider the following Circular Queue.
0 1 2 3 4
60 70 30 40 50
rear front
Delete an element : deleted element is 40. After deletion queue will be
0 1 2 3 4
60 70 30 50
rear front
0 1 2 3 4
60 70 30
front rear
Displaying the elements of the Queue : To display the elements of the Circular
Queue :
1. Check, whether there are elements in Circular Queue.
If there are elements, display them from front position to rear position.
{ System.out.println("3.Display");
System.out.println("Enter element : "); System.out.println("Enter ur choice");
el=sc.nextInt(); k=sc.nextInt();
if(front==-1&&rear==-1) switch(k)
front=rear=0; {
else case 1:q.insert();break;
rear++; case 2:q.del();break;
a[rear]=el; case 3:q.disp();break;
} }
} System.out.println("Do u continue
void del() (Y/N)");
{ ch=sc.next().charAt(0);
if ((front==-1&&rear==-1)|| }while(ch=='y');
(front>rear)) }
System.out.println("Queue is }
empty, no elements to remove.");
else
{ 4) Program to perform queue operations by
System.out.println("Removed element using linked list
is"+a[front]);
front++; import java.util.*;
} class node
} {
void disp()
int a;
{
node next;
if ((front==-1&&rear==-1)||
}
(front>rear))
System.out.println("Queue is empty, class que
no elemenets to display. "); {
else node front,rear;
{ que()
for(int i=front;i<=rear;i++) {
System.out.print(a[i]+"\t"); front=rear=null;
}}} }
void insert()
class queuearray {
{ int el;
public static void main(String args[]) Scanner sc=new Scanner(System.in);
{
System.out.println("Enter element : ");
int k;
el=sc.nextInt();
char ch;
node n=new node();
Scanner sc=new Scanner(System.in);
que q=new que(); n.a=el;
do n.next=null;
{ if(front==null)
System.out.println("1.Insert"); front=n;
System.out.println("2.Delete"); else
rear.next=n; k=sc.nextInt();
rear=n; switch(k)
} {
void del() case 1:q.insert();break;
{ case 2:q.del();break;
if (front==null&&rear==null) case 3:q.disp();break;
System.out.println("Queue is empty, no }
elements to remove."); System.out.println("\nDo u continue (y/n)");
else ch=sc.next().charAt(0);
{ }while(ch=='y');
System.out.println("Removed element is : }
"+front.a); }
front=front.next;
if(front==null)
rear=null; 5) Program to perform circular queue
} operations
}
void disp() import java.util.*;
{ class cque
if (front==null&&rear==null)
{
final int max=5;
System.out.println("Queue is empty, no
int a[]=new int[max];
elements to display.");
int front,rear,count;
else
cque()
{ {
node temp=front; front=-1;
while(temp!=null) rear=-1;
{ count=0;
System.out.print(temp.a+"\t"); }
temp=temp.next; void insert()
}}}} {
public class listque int el;
{ Scanner sc=new Scanner(System.in);
public static void main(String args[]) if ((front==0&&rear==max-1)||
{ (front==rear+1))
System.out.println("Circular queue is
int k;
full.");
char ch;
else
Scanner sc=new Scanner(System.in);
{
que q=new que(); System.out.println("Enter element : ");
do el=sc.nextInt();
{ if(front==-1&&rear==-1)
System.out.println("1.Insert"); front=rear=0;
System.out.println("2.Delete"); else if(front!=0&&rear==max-1)
System.out.println("3.Disp"); rear=0;
System.out.println("Enter ur choice : "); else
{ switch(k)
System.out.println(" Insert at\n\t1.Left\t\t {
2.Right\nEnter Your Choice : "); case 1: System.out.println("Removed element
k=sc.nextInt(); at left is : " +a[left]);
switch(k) if(left==max-1)
{ left=0;
case 1: System.out.println("Enter element to else
insert at left:"); left++;
el=sc.nextInt(); count--;
if(left==-1&&right==-1) break;
left=right=0;
else if(left==0) case 2: System.out.println("Removed element
left=max-1; at right is : " +a[right]);
else if(right==0)
left --; right=max-1;
a[left]=el; else
count++; right--;
break; count--;
break;
case 2: System.out.println("Enter element to }}}
insert at right : ");
el=sc.nextInt(); void disp()
if(left==-1&&right==-1) {
left=right=0; if (count==0)
else if(right==max-1) System.out.println("Dqueue is empty, no
right=0; elemenets to display. ");
else else
right++; {
a[right]=el; int i;
count++; if(left > right)
break; {
}}} for(i=left;i<=max-1;i++)
void del() System.out.print(a[i]+"\t");
{ for(i=0;i<=right;i++)
int k; System.out.print(a[i]+"\t");
Scanner sc=new Scanner(System.in); }
if (count==0) else
System.out.println("Dqueue is empty, no {
elements to delete."); for(i=left;i<=right;i++)
else System.out.print(a[i]+"\t");
{ }}}}
System.out.println(" Delete at\n\t1.Left\t\t class dqueue
2.Right\nEnter Your Choice : "); {
k=sc.nextInt(); public static void main(String args[])
{
int k;
char ch;
Scanner sc=new Scanner(System.in);
dque d=new dque();
do
{
System.out.println("1.Insert");
System.out.println("2.Delete");
System.out.println("3.Display");
System.out.println("Enter ur choice : ");
k=sc.nextInt();
switch(k)
{
case 1:d.insert();break;
case 2:d.del();break;
case 3:d.disp();break;
}
System.out.println("\nDo u continue (y/n) : ");
ch=sc.next().charAt(0);
}while(ch=='y');
}}