0% found this document useful (0 votes)
2 views

2

This document provides an overview of stacks and queues, detailing their definitions, operations, advantages, disadvantages, and applications. It explains stack operations such as push and pop, and queue operations like insertion and deletion, along with algorithms for converting infix expressions to postfix and evaluating postfix expressions. Additionally, it discusses various types of queues, including circular and priority queues, and introduces heaps.

Uploaded by

ammu02829
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

2

This document provides an overview of stacks and queues, detailing their definitions, operations, advantages, disadvantages, and applications. It explains stack operations such as push and pop, and queue operations like insertion and deletion, along with algorithms for converting infix expressions to postfix and evaluating postfix expressions. Additionally, it discusses various types of queues, including circular and priority queues, and introduces heaps.

Uploaded by

ammu02829
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIT-2

STACKS AND QUEUES


STACK:

A stack is an ordered collection of items into which new items may be inserted
and existing items may be deleted at one end called as the top of the stack. A stack is
also known as LIFO structure because element which is inserted last is the first
element to be deleted.
By the definition of the stack there is no upper limit on the number of
items that can be kept in a stack on pushing an element stack grows while popping an
element stack shrinks.

Representation of Stack:

Basic Stack Operations:

Push operation

The method of inserting an element into a stack is called as ‘push’. It adds a


new item on a top of the stack. Top is incremented by 1, each time when an element
is inserted onto to the stack. Stack is also known as last-in-first-out structure because
element which is inserted last is the first element to be deleted. Push operation is
nothing but writing values onto to the stack when a stack is full, no element can be
inserted and this situation is called as stack overflow.

1
Algorithm for Push operation:

1. push(int x)
2. begin
3. if(top>=n-1)
3.1 printf("stack overflow insertion is not possible\n");
3.2 return;
4. end if;
5. top=top+1;
6. stk[top]=x;
7. printf("inserted %d\n",x);
8. end push();
Deletion operation

The method of deleting an element from stack is called “POP” operation. It


deletes the top most elements present on the stack. Top is decremented by 1, each
time when an element is deleted from the stack. Pop operation is nothing but deleting
an element from the stack. When stack is empty no element can be deleted and this
situation is called as stack “UNDERFLOW”.

Algorithm for POP operation

1. pop()
2. if(top<0)
2.1 printf("stack empty deletion is not possible\n");
2.2 return(0);
3. end if;
4. else
4.1 printf("deleted\n");
4.2 top=top-1;
4.3 return(stk[top]);
5. end else;
6. end pop();

Example:

2
The following figure illustrates how push and pop operations are performed on the
stack

Advantages and disadvantages of Stack

Advantages:
1. push/pop operation can be done easily.
2. Stack can be used to perform mathematical computation i.e., conversion of infix to
postfix etc.
3. Stacks are used in handling elements with particular order.
Disadvantages:
1. Stack consists of single pointer. If the value of that pointer is lost, then it is
possible to access the remaining elements of the stack.
2. The elements which was first inserted is the last one to be accessed
3. If the elements are pushed very frequently, when compared to popping elements
then the first element that was inserted will never be accessed.

Representation of stack using arrays:

Stack can be a managed easily by using array, since an array generally stores
an ordered list of item. But the drawback of representing the stack using arrays is
that, the size of array need to be declared before it is used in a program. This implies
3
that the size of an array must be static (i.e., it cannot be modified once declared) on
the other hand as the elements in the stack need to be inserted or deleted, the size of
the stack cannot be fixed.

Even though an array differs from a stack the former


can be used for storing the stack elements. The size of array can be declared to be
maximum enough for managing a stack. Because of this the size of the stack can
either increase or decrease within a reserved memory space.
Before an implementation of stack using arrays it is necessary to verify whether
the stack is empty (or) full. If the stack is empty the deletion cannot be performed and
if the stack is full, insertion is not possible.

Here the top is pointed to the position of the array i and u denotes the index
range of the array. First, memory has to be allocated for the given capacity of the
array of the stack then; right from the first position the elements are stored onto the
stack sequentially. From the figure A[j] represents the jth element and top is the
pointer within which the insertion (or) deletion is done.
There are two conditions to represent a stack condition.
(1)If empty top<1
(2)If stack is full ,it should satisfy the condition top>=u

Stack Applications:

Applications of stack in reversing list:

Let us understand stack application of reversing data elements by taking the list of
elements. Reversing the elements of a list include , creating of stack, which reads the
elements of list and performs a ‘push’ operation, to store them in Last-In-First-
4
Out(LIFO). After pushing all elements of the list on to the stack, which displays the
elements of the list in reverse order.

Factorial Calculation using stack


The following pseudo-code for computing factorial of a given number, shows how
stack data structure is helpful in handling recursion
fact(int n)
begin
if(n<=1)
return 1;
else

5
return n*fact(n-1);
end
The step 3 in the code is a base case, where 0! Results 1 (i.e. when n<=0). This case
is required in order to avoid an infinite number of calls to the ‘fact’ function during
computation of n!
Based on the value of n, the procedure calls to itself for a number of times, which
shows the replication of fact(), with different values. These procedures are expected
to end in a normal way, before the value of n! is displayed, by the function fact(),
when it is called for the first time. There are two cases in which, a procedure ends in
the normal way.
(i) When base case execution is ended or
(ii) When recursive case execution is ended successfully.

The stack data structure is used to maintain the values of all variables during
procedure call and to follow the calls made to the procedure itself, while the execution
is in progress. To understand the usage of stack data structure, consider the
execution of fact(5). The values of the variable n are maintained by stack data
structured for every call.

Infix to
postfix

Transformation:

Let us consider “Q” is an expression written in infix notation and the algorithm
finds the equivalent postfix notation “P”.

Algorithm:

Step 1: Push “(“left parenthesis onto stack and “)” right parenthesis to the end of Q
(expression)
6
Step 2: Scan Q from left to right and repeat steps 3 to 6 for each element of Q until
the stack is empty.
Step 3: If an operand is scanned, add it to P.
Step 4: If a left parenthesis is scanned, push it onto stack.
Step 5: If an operator is scanned, then repeatedly POP the topmost operator from the
stack and we have to comparison between scanned operator & popped
operator from the stack. If popped operator is same or higher precedence
than scanned operators then popped operator add to P, otherwise back to
push into stack and scanned operator add to stack.
End of if statement.
Step 6: If a right parenthesis is scanned, then repeatedly pop each operator from
stack and add to P until the left parenthesis is encountered.
Step 7: remove the left parenthesis and don’t add this parenthesis to P.
End of if statement.
End of step 2 loop.
Step 8: exit.

Example: 5+3*6-(6/2)
POSTFIX EXPRESSION
SCANNED SYMBOL STACK
(P)
( (
5 ( 5
+ (+ 5
3 (+ 53
* (+* 53
6 (+* 536
- (- 536*+
( (-( 536*+
6 (-( 536*+6
/ (-(/ 536*+6
2 (-(/ 536*+62
) (- 536*+62/
) EMPTY 536*+62/-

Output Is: 536*+62/-

Evaluation of postfix Expression:


Algorithm:
This algorithm finds the final value of an arithmetic expression which is written
in postfix notation.
Step 1: Add a right parenthesis “)” at the end of postfix Expression (This act as a
sentinel)
Step 2: scan postfix expression from left to right and repeat steps 3 and step 4 for
each element of postfix expression until the sentinel “)” is encountered.
Step 3: If an operand is scanned, add it onto stack.

7
Step 4: If an operator is scanned, then
a) Remove the two top elements from stack, where A is the top element
and B is the next top element
b) evaluate B*A
c) Place the result of (b) back onto stack
End of if statement
End of step 2
Step 5: Set value equal to the top element on stack
Step 6: Exit.

Example: 536*+62/-

6
3
5

18
5
3*6

23
5+18

2
6
23

3
23
6/2

20
23-3

The Evaluation Of given Postfix Expression is 20.

Queue:
A queue is an ordered collection of items in which new items may be inserted at
one end known as rear end and existing items may be deleted from other end known
as front end.
Queue is also known
as First- in-First-Out
(FIFO) structure

8
because the element which is inserted first will be the first element to be deleted.
Diagrammatically is shown as.

Basic Queue operations:

(a) Insertion Adds new item at rear end of queue

(b) Deletion Deletes an item from front end of queue.

Queues are implemented sequentially in C using an array. Two variables ‘front’


and ‘rear’ hold the position of first and last elements in queue respectively. Queue can
have 0 to MAX-1 elements where MAX is the size of array.

Initially when queue is empty, front=rear=-1.

Insertion Operation:

Insertion Operation performs the following actions.

1. If rear==MAX-1 i.e., queue is full, then prints a message that ‘queue is full’ and
no new element can be added to queue

2. Otherwise, increments rear by 1 and inserts new element at rear position.

Algorithm /*Inserting an element into queue*/

insert(int data)
if(r==n-1)
display "queue overflow insertion is not possible";
else

9
r=r+1;
q[r]=data;
display "inserted data value”,
end else block;
end insert();
Deletion Operation

Deletion operation perform the following actions


1. If the queue is empty which is given by front=-1, the prints a message that “no
deletion is not possible”.
2. Otherwise, retrieves the front element and then increments front by 1.

Algorithm /*Deletion from a queue*/

deletion()
int z;
if(f==r)
display "queue empty deletion is not possible";
f=-1;
r=-1;
return(0);
end if;
else
display "deleted";
f=f+1;
z=q[f];
return(z);
end else block;
end deletion();

Queues are represented using arrays

Array is a one dimensional structure, which can be used to represent a queue


with two pointers named, FRONT AND REAR
Before inserting elements into queue, we need to check whether the
queue is full if so, insertion cannot be performed. Similarly, if the queue is empty,
deletion cannot be performed.
10
Implementation of queue operations using stack

Implementation of queue can also be done by using two stacks.


There are two methods to implement queues using stack.
1. By making data movements in enqueue operation.
2. By making data movements in dequeue operation.

The following solution assumes the implementation of queue using Stacks


Now, let there be two Stacks S1 & S2, we need to use these two stacks to implement
a Queue.

Consider the following:

For enqueue operation:

 If Stack S1 is full , thus an overflow has occurred , we throw an error message

 Else , we push the value into S1

Thus following multiple enqueue operations, the situation would be like:

11
For dequeue operation:

 If stack S1 is empty , thus an underflow condition has occurred , throw an error

 Else , we copy all except the last element of S1 into S2 , We return the last
element.

Now we can delete the elements in s2 the top element in stack s2 is 20.
Therefore the queue principal is First-in-First-Out (FIFO) is satisfied by using stacks
operations.

The 20 is the first element in queue and this 20 come out from the stack first.
So by this process Implementation of queue operations using stack is done.

12
Applications of queue

Round Robin Algorithm

Circular Queue
Let we have an array Q that contains n elements in which Q[1] comes after Q[n]
in the array. When this technique is used to construct a queue then the queue is
called circular queue. In other word we can say that a queue is called circular when
the last element comes just before the first element.

There is types of pointer called front and rear is used to assume the front side
and rear side of the circular queue. In a circular queue when rear = n, if we insert an
element then this element is assigned to Q[1]. That is instead of increasing rear to
n+1, we reset rear to 1. Similarly if front = n and an element of the queue is removed,
we reset front to 1 instead of n + 1. Suppose queue contains only one element that is
front=rear not equals to NULL and suppose that the element is removed then the
front and rear pointer are now assigned NULL to indicate that the queue is empty.

13
Priority Queue:
A Priority queue is a collection of elements where the elements are stored according
to their priority levels. The order in which the elements should get added or removed
is decided by the priority of the element.
Following rules are applied to maintain a priority queue.

1. The elements with a high priority are processed before any element of lower priority.

2. If there are elements with the same priority, then the element added first in the queue would
get processed.

Priority queue is used in Operating Systems for scheduling jobs where jobs with higher
priority are processed first.

Heap: Heap is a complete Binary tree and there are two types of heaps.

Type 1: Max-Heap: If the value present at any node is greater than all its
children then such a tree is called as the Max-Heap or Descending
Heap.
Type 2: Min-Heap: If the value present at any node is smaller than all its
children then such a tree is called as the Min-Heap or ascending Heap.

14

You might also like