You are on page 1of 17

UNIT-2

STACKS
A Stack is a Linear data structure in which an element may be inserted and deleted only at one
end called Top of the stack.

A Stack is called LIFO (Last in First Out) structure because the last element to be added to a stack
is the first element to be removed. The other name of stacks is piles or push down list.

STACK OPERATIONS

THREE basic operations associated with stacks :-

1. Push 2.POP 3.Traverse

Push is adding or inserting element into stack.

Pop is delete or removing element from the stack.

Traverse is visiting each element at least once.

IMPLEMENTATION

Meaning :-The act of implementing (providing a practical means for accomplishing something);

STACK IMPLEMENTATION / REPRESENTATION

Stacks can be implemented in two ways :-

1. Static or Array Implementation

2. Dynamic or Linked List Implementation

Static Implementation uses Arrays to create stack.

Dynamic implementation uses pointers to implement stack by linked lists.


Stack Overflow:-While inserting new element if there is no Room then it is called Overflow condition
.Here Top is at highest location in stack

Stack Underflow / Empty:- while removing an existing element if there is no element present in the
stack ,this condition is called as Underflow condition.

1.ALGORITHM FOR PUSH OPERATION

PUSH(STACK,TOP,MAX,ITEM)

Step 1. [stack already filled ? Check For Overflow ]

If TOP := MAX-1 , then Write “ OVERFLOW ” & EXIT

Step 2. Set TOP := TOP +1 [increase TOP by 1]

Step 3. Set STACK[TOP]:= ITEM [ Insert ITEM in new Top Position]

Step 4. Return OR EXIT

2.ALGORITHM FOR POP OPERATION

POP ( STACK, TOP, ITEM)

Step 1. [Is their any item in the stack ? Check for Underflow ]

If TOP := -1 , then Write “ UNDERFLOW ” & EXIT

Step 2. Set ITEM := STACK[TOP] [ASSIGN TOP ELEMENT TO ITEM]

Step 3. Set TOP :=TOP - 1 [ decrease top by 1]

Step 4. Return OR EXIT

APPLICATION OF STACKS

1.Reversing a String
The stack can be used to reversing the order of execution. Ex. is Reverse the strings of line of
characters.

2.Calculation of Postfix Notation & Evaluation of Postfix Notation

There are basically 3 types of Notations for an expression:-

1. INFIX NOTATION 2. PREFIX NOTATION 3.POSTFIX NOTATION

INFIX NOTATION

In arithmetic expression, when the operator symbol is placed between its operand it is called as INFIX
NOTATION.

E.g. A + B , X- Y , G / H

POLISH NOTATION (PREFIX NOTATION)

This notation is named in the name of Polish Mathematician Jan Lukasiewicz , In which operator is
placed before its operand.

e.g. A+ B -> + AB

C–D -> - CD

The advantage of this notation is, arithmetic expressions are evaluated without parenthesis. Due to
absence of parenthesis it becomes easier for the compiler to translate and execute it

REVERSE POLISH NOTATION(POST FIX NOTATION) / SUFFIX NOTATION

In this notation the operator symbol is placed after its operands. Parenthesis are not used to
determine the order of evaluation

e.g. A + B -> AB +

C+D -> CD +

G/H -> GH /

NOTATION CONVERSIONS

Conversion one notation to another notation is possible .

That is infix to prefix, infix to postfix , prefix to infix , postfix to infix

Operator Precedence

Exponential Operator ^ or ↑ ---- Higher Precedence

Multiplication / Division * , / ---- Next precedence

Addition / Substraction + , - -----Least precedence


ALGORITHM FOR CONVERTING INFIX NOTATION INTO POSTFIX NOTATION

Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the equivalent
postfix expression P.

1. Push “ ( “ onto STACK, and add “ ) “ to the end of Q.

2. Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the stack is empty.

3. If an operand is encountered , add it to P.

4. If a left parenthesis is encountered , push it onto STACK.

5. If an operator is encountered then :

(a). Repeatedly pop from STACK & add to P each operator which has same precedence as or
higher precedence than .

(b) Add to STACK.

[End if ]

6. If a right parenthesis is encountered then :

(a) Repeatedly Pop from STACK and add to P each

operator until a left parenthesis is encountered.

(b) Remove the left parenthesis. [do not add to P]

[End if ]

[End of step 2 loop]

7. Exit

ALGORITHM FOR EVALUATION OF POST FIX NOTATIONS

Step 1. add a right parenthesis “ ) ” at the end of P.

Step 2. Scan P from left to right & repeat steps 3 and 4 for each element of P until the “ ) “ is
encountered.

Step 3. If an operand is encountered, put it on STACK.

Step 4. If an operator is (x) encountered then :

(a) Remove the top two elements of STACK, where A is the

top element and B is the next to top element.

(b) Evaluate B [x] A.


(c) Place the result of (b) back to STACK.

[End of IF]

[End of step 2 loop]

5.Set VALUE equal to the top element on STACK.

6.Exit

ALGORITHM FOR CONVERSION OF INFIX TO PREFIX EXPRESSION

Suppose Q is an arithmetic expression written in infix notation.

This algorithm finds the equivalent prefix expression P.

1)Reverse the infix expression

Write steps(1 to 6) for INFIX to POSTFIX conversion here…............

9) Reverse the Expression

EVALUATION OF PREFIX NOTATION

This algorithm finds the VALUE of an arithmetic expression P written in prefix notation.

1. Add a left parenthesis “ ( ” at the beginning of P.

2. Scan P right to left & repeat steps 3 and 4 for each element of P until the “ ( “ is encountered.

Here all the steps are same as evaluation of Postfix notation so write all the points……………

5. Exit

CONVERSION OF POSTFIX TO INFIX AND PREFIX TO INFIX WRITE FROM TEACHER.


CHARACTERISTICS OF STACK

[Do one diagram for stack] and [do one diagram each for array and linked representation of stack and
label it ]

Stack is a LIFO type of data structure in which insertion is done from the top of the stack and the last
added element will be the 1st to be removed from the stack.

Stack always contains a variable called Top which always points to the TOP element of the stack.

When the stack contains no elements then it is called Underflow condition.

When the stack is full so that no element can be added , this is called overflow condition . This overflow
condition will arise when the size of the stack is fixed that is whenever we are implementing static data
structure by using array.

We can apply many operations on stack like push, pop , display, traverse .

Stacks can be implemented in 2 ways :-Static implementation and dynamic implementation.

The static implementation used array to create stack. It is a simple technique but is not a flexible way of
creating stack as the size is fixed during compilation time. So no increase or decrease of size can be
done.

The dynamic implementation stacks are implemented by Linked list using pointers so we can increase or
decrease the size of the stack.
LINK OR DYNAMIC IMPLEMENTATION OF STACK

Stacks can be implemented by linked list. It uses pointers to link one element to another. The insert and
delete operations can only be performed at the beginning but not any other positions because it is a
LIFO structure.

TOP is the pointer variable which points to 1st element of the list. When any element is added then TOP
points to it. Here no overflow condition is present as dynamic in nature.

struct node

Int info;

struct node *link;

struct node *TOP=NULL;

PUSH operation in Stack(Linked representation) (algorithm)

Step 1. set Top=NULL

Step 2. temp= (struct node *) malloc(sizeof(struct node))

Step 3. temp-> info = item

Step 4. temp->link =Top

Step 5. Top= temp

step 6. exit

Pop Operation in Stack (linked representation) (algorithm)

Step 1. if Top ==NULL then

write “ stack is empty “ and exit

Step 2. temp=Top

step 3. Top = Top - > link

Step 4. free (temp)


Step 5. exit

Display or Traverse Operation in Stack(linked representation) (algorithm)

Step 1. If Top ==NULL then write “stack is empty” and exit

Step 2. set temp=Top

Step 3. repeat while temp !=NULL

Step 4. Write temp->info

Step 5. temp=temp->link

[end of while]

Step 6. Exit

Recursion
A function that calls itself is called a recursive function and this technique is called recursion. A

recursive function will call itself until a final call that does not require a call to itself is made. It

takes advantage of the system stack to temporarily store the calling function’s return address and

local variables.

There are two major cases in any recursive solution. They are

Base case in which the problem is simple enough to be solved directly without the need for any
more calls to the same function

 Recursive case
o The problem at hand is initially subdivided into simpler sub-parts.
o The function calls itself again, but this time with sub-parts of the problem obtained in the
first step.
o The final result is obtained by combining the solutions of simpler sub-parts.

A recursive function is said to be well-defined if it has the following two properties:

 here must be a base criteria in which the function doesn’t call itself.
 Every time the function is called itself, it must be closer to the base criteria.

Factorial Function
To illustrate recursive functions, consider calculating the factorial of an integer.

The product of the positive integers from 1 to n is called n factorial denoted by n!


. To find n!, multiply the number by the factorial of the number that is one less than the number.

That is,

n! = n * (n - 1)!

Assume we need to find the value of 5!.

Then,

5! = 5 * 4!
, where
4! = 4 * 3!

Therefore,

5! = 5 * 4 * 3!

Factorial of a given number


#include <stdio.h>

int Fact(int);

int main()

int num, val;

//read a number from the user

printf("Enter the number: ");

scanf("%d", &num);

//call fact function

val = Fact(num);

//print result

printf("Factorial of %d = %d", num, val);


return 0;

//function to calculate factorial

int Fact(int n)

if (n == 1)

return 1;

else

return (n * Fact(n-1));

Output

Enter the number: 5

Factorial of 5 = 120

TYPES OF QUEUE

1.SIMPLE QUEUE

2.CIRCULAR QUEUE
3.DEQUEUE(Double ended queue)

4.PRIORITY QUEUE

Basic Operations in Queue


Below are the basic queue operations in data structure:

Operation Description

enqueue() the process of adding or storing an element to the end of the queue

dequeue() the process of removing or accessing an element from the front of the queue

peek() it is used to get the element at the front of the queue without removing it

initialize() creates an empty queue

isfull() it checks if the queue is full

isempty() it is used to check if the queue is empty

The Queue Implementation/Representation


We can implement Simple Queue by the following method

1. Array or static

2. Link list or Dynamic

ARRAY REPRESENTATION / STATIC REPRESENTATION SIMPLE QUEUE

We can implement Queue by using Arrays. Here we know about exact no. of elements to store in a
Queue.

The total no of elements present in the queue can be known by relation:-

Total No. of elements := front - Rear+1


Queue[5] is an Array

Max- Maximum no. of elements

Front - Location of Front element

Rear - Location of Rear element.

Initially queue is Empty So , Front = Rear = -1

When an element is added in queue its rear is increased by 1 i.e. Rear := Rear +1

Whenever an element is deleted from queue its front is increased by 1. i.e. Front := Front +1

For the first time when we add one element in a queue its front and rear both increased by 1 after that
only rear will increases but not front.

When the queue totally full then it is called Overflow condition. Whereas when there is no element in

the queue to delete it is called Underflow condition.

INSERT ALGORITHM(FRONT,REAR, MAX, QUEUE,ITEM)

Step 1. [check for overflow]

If REAR == MAX -1 then : Write “ Overflow “ and exit.

Step 2. if FRONT == -1 then :

Set Front := 0 and Rear:=0

[end if]

Step 3. set REAR := REAR + 1

Step 4. QUEUE [REAR]:= ITEM

Step 5. EXIT

DELETE ALGORITHM (FRONT, REAR , MAX , QUEUE ,ITEM)

Step 1. [ Check for Underflow]

If FRONT == -1 or Front < 0 then :


Write “ Underflow condition” and Exit.

Step 2. Set ITEM : = QUEUE [FRONT]

Step 3. if FRONT == REAR then :

Set FRONT := -1 and REAR := -1

[end if]

Step 4. Set FRONT := FRONT +1

Step 5. Exit

Link or Dynamic Implementation of Simple Queue

Queue can be implemented by Linked list dynamically .

It is a easy technique to insert or delete element from any position of the list. It takes more memory
space than array representation due to use of one more pointer field. Two pointers Front and Rear to
point 1st and last element respectively.

ALGORITHM FOR INSERT IN QUEUE

Step 1. set Front = Null and Rear=Null

Step 2. Set tmp=(struct node *)malloc(sizeof(struct node))

Step 3. tmp->info = item

Step 4. tmp->link=NULL

Step 5. If Front == NULL then

Set Front = tmp , Rear=tmp

Step 6. else Rear->link=tmp

Step 7. Rear= tmp

Step 8. Exit

ALGORITHM FOR DELETE IN QUEUE

Step 1. if Front = =NULL ,Write “ Queue Underflow” & exit

Step 2.tmp= Front


Step 3. Front= Front->link

Step 4. free(tmp)

Step 5. Exit

Advantages of Simple Queue

1. It is Simple to Use & Reflects True resemblance with Real World.

Limitations & Disadvantages of Simple Queue

1. Disadvantage of Simple Queue is when it is implemented using Array is:- when the Rear reaches
at last location after that we can’t insert more elements into the queue though the queue is
empty , if we try to do so it flashes message that Queue is Full .

2. One rule is that we can insert elements at the Rear and Delete from Front so at any position
insertion and deletion in linked implementation of queue is violates the rule.

3. The Limitations of simple queue can be overcome upto some extent in Circular queue.

2.CIRCULAR QUEUE
In Circular Queue the insertion of a new element is done at the very first location of the queue when the
last location is full. So we can say that a circular queue is one in which the first element comes just after
last element.

Diagram :- do from your teacher (two types)

If we have a Queue of say N elements then after inserting an element last(n-1th) location of the array the
next element will be inserted at the very first location (i.e. location with subscript zero).it is possible only
if the first location is empty.

Circular queue can be implemented in two different ways :-

1.Static 2. Dynamic

STATIC OR ARRAY IMPLEMENTATION OR REPRESENTATION

A circular queue can be implemented in an array using two variables FRONT and REAR. FRONT and
REAR keeps track of the elements to be deleted and inserted respectively.

ALGORITHM FOR INSERT AN ELEMENT IN CIRCULAR QUEUE

Step 1. if Front = = 0 and Rear= =max-1

OR Front= =Rear+1 then Write “Overflow” and exit.

Step 2. if Front==-1 then set Front =Rear= 0

else if Rear==max-1 then set Rear=0


else

Rear=Rear+1

[End of If]

Step 3. set Queue[Rear]=ITEM

Step 4. Exit.

ALGORITHM FOR DELETE AN ELEMENT IN CIRCULAR QUEUE

Step 1. if Front = = -1 then Write “Underflow” and exit.

Step 2. set ITEM=Queue [Front]

Step 3. if Front= =Rear then set Front=-1 , Rear=-1

else if Front==max-1 then set Front=0

else

set Front=Front+1

[end if]

Step 4. Exit.

LINKED IMPLEMENTATION OF CIRCULAR QUEUE(DYNAMIC REPRESENTATION)

In linked implementation of queue two pointers Front and Rear points to the 1st and last node of the
circular queue.

When circular queue is implemented using linked list it has no fixed size, so we can continue inserting
node at the rear side and the last node contains the address of the first node.

Recall in array representation when REAR and FRONT reaches at last then both reset to 0 i.e. first
position , so this situation will not occur in linked implementation as no overflow condition is present.
INSERT OPERATION

Step 1. ptr= (struct node *) malloc(sizeof(struct node))

Step 2. ptr -> info =item

Step 3. if Front= Null then

Front = Rear = ptr

else

Rear->link=ptr

Rear=ptr

Step 4. Exit

DELETE OPERATION

Step 1. if Front = = Null then Write “Underflow and Exit

Step 2. set tmp =Front

Step 3. if Front==Rear!= =Null then Set Front=Rear=Null

[End if]

Step 4. Front=Front->link

Rear->link=Front

Step 5. Free(tmp)

Step 6. Exit

Advantages

1.A circular queue overcomes the problem of unutilised space in simple queue implemented as array

2. Simple to insert and delete and proper utilisation of memory.

3.Logically and practically seems appropriate.

Disadvantages

1.Here retrieval of data is performed on the basis of FIFO order but in real time systems we need data
retrieval by highest priority tasks first. So this is found in Priority Queue.

3. Priority Queue

In a priority queue, the nodes will have some predefined priority in the priority queue. The node
with the least priority will be the first to be removed from the queue. Insertion takes place in the
order of arrival of the nodes. The applications of priority queue include Dijkstra’s shortest path
algorithm, prim’s algorithm, and data compression techniques like Huffman code.

4. Dequeue (Double Ended Queue)

In a double ended queue, insertion and deletion can take place at both the front and rear ends of
the queue.

APPLICATIONS OF QUEUE
Queue is used when things don’t have to be processed immediately, but have
to be processed in First In First Out order. This property of Queue makes it also
useful in following kind of scenarios.
1) When a resource is shared among multiple consumers.
Examples include CPU scheduling, Disk Scheduling.
2) When data is transferred asynchronously (data not necessarily received at
same rate as sent) between two processes. Examples include IO Buffers, pipes,
file IO, etc.
3) In Operating systems:
a) Semaphores
b) FCFS ( first come first serve) scheduling, example: FIFO queue
c) Spooling in printers
d) Buffer for devices like keyboard
4) In Networks:
a) Queues in routers/ switches
b) Mail Queues
5) Variations: ( Deque, Priority Queue, Doubly Ended Priority Queue )
Some other applications of Queue:
 Applied as waiting lists for a single shared resource like CPU, Disk, Printer.
 Applied as buffers on MP3 players and portable CD players.
 Applied on Operating system to handle interruption.
 Applied to add song at the end or to play from the front.

******

You might also like