0% found this document useful (0 votes)
118 views35 pages

Unit 1 Stack (DSA)

Data structures are methods of organizing and storing related information efficiently for processing with algorithms. They can be categorized into primitive and non-primitive types, with linear and non-linear structures, such as stacks and trees. The document also discusses stack operations, implementations, and applications, including factorial calculation and list reversal.

Uploaded by

Sankalp Rawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
118 views35 pages

Unit 1 Stack (DSA)

Data structures are methods of organizing and storing related information efficiently for processing with algorithms. They can be categorized into primitive and non-primitive types, with linear and non-linear structures, such as stacks and trees. The document also discusses stack operations, implementations, and applications, including factorial calculation and list reversal.

Uploaded by

Sankalp Rawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Data Structures & Algorithms(3CS4-05)

What is Data Structure?

• It is way of storing related information


• It is way of organizing data so that it can be used effectively
• It is way for organizing, processing, retrieving and storing data

Data Structure consists of two things:


1. Type of structure we use to store data
2. How efficiently we perform operations on that data so that it results
in less execution time and amount of memory space required.

Operations: Insertion, deletion, traversing, searching, sorting etc.


In computer programming data structure designed to store data for
the purpose of working on it with various algorithms.

Data Structure contains information about the data values, relationship


between the data and functions that can be applied to the data.
Type of Data Structure

Primitive Data Structure Non-Primitive Data Structure

• Integer
• Float Linear Data structure Non Linear Data structure
• Character
• Array • Tree
• Stack • Graph
• Queue • Hash Table
• Linked list
Linear Data structure : In this elements are stored in contiguous memory locations or are arranged sequentially.
It can be constructed by using an array. The adjacency relationship is maintained between
elements.
e.g. Array, Stack, Queue, Linked List

Non Linear Data structure: In this the elements are not arranged sequentially or linearly. The adjacency
relationship is not maintained between data elements. They are not easy to
implement as compare to linear data structure. Data elements are attached in
hierarchical manner. Manoj Kataria BKBIET, pilani
e.g. Tree, Graph
STACKS(Unit-1)
Stack: It is a linear data structure in which elements are inserted and deleted only from one end, called top of stack.
It is LIFO(Last In First Out) the element inserted in last is taken out first or FILO(First In Last Out) the element
inserted in first is taken out in last. LIFO(Last In First Out)
e.g. Deck of cards
Stack of plates in cafeteria FILO(First In Last Out)

PUSH POP 4 MAX


(insertion) (deletion) 3
60 2 Top of stack (TOP)
40 1
20

There are two basic operations of stack: PUSH and POP


Inserting an item in stack is termed as PUSH and deleting an item from stack is termed as POP.
When item is pushed into stack, TOP is incremented by one and when item is popped, TOP is decremented by
one.
When TOP=-1 means stack is empty (POP operation is not possible , stack is underflow)
When TOP=MAX-1 means stack is full (PUSH operation is not possible, stack is full)
Manoj Kataria BKBIET, pilani
4 MAX-1 4 4 100 4 TOP
3 3 3 80 3
2 2 2 60 2
1 1 40 1 TOP 40 1
20 TOP 20 20
initially stack is PUSH first element i.e. PUSH second element i.e. 40 PUSH fifth element i.e100
empty 20 TOP=TOP+1 or TOP++ TOP=TOP+1 or TOP++
TOP=-1 TOP=TOP+1 or TOP++ Top=MAX-1 so stack is Full
PUSH operation

4
4 4
3
3 3
2
60 2 TOP 2
1
40 1 40 1 TOP
20 TOP
20 20
POP top element POP top element
TOP=TOP-1 or TOP-- TOP=TOP-1 or TOP--
Manoj Kataria BKBIET, pilani
POP operation
A stack can be implemented in two ways:
1. Using array - Static implementation
2. Using Linked List - Dynamic implementation

Static array representation of stack: we take an array of fixed size, so that we can’t push more elements in the stack
more than the size of stack.
e.g. #define MAX 10
int s[MAX]; or int s[10];

PUSH operation:
Steps: 1. Check if stack is Full
2. If stack is Full, then print “Overflow” and exit
3. If stack is not Full, increment TOP by one to point to next memory space
4. Add data item
5. Exit

Algorithm: PUSH operation


if(top==MAX-1)
print “Stack is Full” and return
endif
set TOP=TOP+1
s[TOP]=item
Manoj Kataria BKBIET, pilani
4 MAX-1 4 MAX-1
3 3
/*push function */ 2 2
void push(int item) 1 1
{ 20 TOP
if(top==MAX-1) PUSH first element i.e. 20
initially stack is
printf(“\n Stack is full”); empty TOP=TOP+1 or TOP++
else TOP=-1
{
90 4 TOP
top=top+1; /*top++*/
80 3
s[top]=item;
2
} 60

} 40 1
20
initially stack is
empty
TOP=-1
Manoj Kataria BKBIET, pilani
POP operation:
Steps: 1. Check if stack is Empty
2. If stack is Empty, then print “Underflow” and exit
3. If stack is not Empty, access the element at the top of stack
4. Decrement TOP by one
5. Exit

Algorithm: POP operation


if(TOP==-1)
print “Stack is Underflow” and return
endif
item =s[TOP]
TOP--;

Manoj Kataria BKBIET, pilani


4
3
2
/*pop function */ 1
void pop( )
{ TOP=-1
if(top==-1) Stack is empty
printf(“\n Stack is empty, underflow”); 4
else 3
{ 60 2 TOP
item=s[top]; /*access element at top of stack*/ 40 1
printf(“\nDeleted element is :%d”,item); 20
top=top-1; /*top--*/ POP top element
} and top=top-1
}

Manoj Kataria BKBIET, pilani


/* program for stack*/ case 2:
#include<stdio.h> pop( ); /calling push function*/
#include<conio.h> break;
#define MAX 10 case 3:
void push(int); display( ); /calling display function*/
void pop( ); break;
void display( ); default:
int s[MAX], top=-1; /*global declaration*/ printf(“\n Choice is wrong”);
void main() } /*end switch*/
{ printf(“\nContinue press 1 for Yes:”);
int choice,item,k=1; scanf(“%d”,&k);
clrscr(); } /*end while*/
while(k==1) }
{
printf(“\n1. Push \n2. Pop \n3. Display \n 4. Exit”);
printf(“\nEnter your choice:”); /*diplay function*/
scanf(“%d”,&choice); void display( )
switch(choice) {
{ int i;
case 1: for(i=0;i<=top;i++)
printf(“\nEnter item to push:”); printf(“%d \n”,s[i]);
scanf(“%d”,&item); }
push(item); /calling push function*/ Manoj Kataria BKBIET, pilani
break;
Multiple stack implementation using single array:
• We can implement two stacks in a single array. While inserting elements in either stack compare TOP of each
other. (TOP1 pointer for stack1 and TOP2 pointer for stack2)
• Both stacks use the same array for storing elements.
• Two PUSH functions and two POP functions.
• This is for utilizing memory space.
• Both stack grow or shrink in opposite direction.
• The first element in stack1 is pushed at index 0. The stack2 starts from rightmost corner, the first element in stack2
is pushed at index MAX=1

stack2 (index MAX-1) 6 MAX-1 stack2


5
4
deletion
insertion 3

stack1
stack1(index 0)

Manoj Kataria BKBIET, pilani


6 6 85 6 top2
5 5 5
4 4 4
insertion
3 3 3

15 top1 15 top1
Intially both stacks are empty PUSH item onto stack1 PUSH item onto stack2
top1=top2=-1 top1=top1+1 top2=MAX-1

85 6
124 5
top2 is decremented for each PUSH operation
100 4 top2
top1 is incremented for each PUSH operation
3
top2 is incremented for each POP operation
56 top1 top1 is decremented for each POP operation
15
Manoj Kataria BKBIET, pilani
//push function for stack1 //push function for stack2
void push1(int item) void push2(int item)
{ {
if(top1==top2-1) if(top2==top1+1)
printf("\nstack is full"); printf("\nstack is full");
else else
{ {
top1++; top2--;
s[top1]=item; s[top2]=item;
} }
} }

Manoj Kataria BKBIET, pilani


//pop function for stack1 //pop function for stack2
void pop1() void pop2()
{ {
int item; int item;
if(top1==-1) if(top2==-1)
printf("\nStack1 is empty:"); printf("\nStack2 is empty:");
else else
{ {
item=s[top1]; item=s[top2];
top1--; top2++;
printf("\nDeleted Element from stack1 is %d",item); printf("\nDeleted Element from stack2 is %d",item);
} }
} }

Manoj Kataria BKBIET, pilani


Stack Applications:
• Factorial calculation
• Reversing list
• Infix to postfix transformation
• Evaluating arithmetic expression
• Tower of Hanoi
Factorial calculation:
Recursion: It is a technique by which a function call itself again and again until a condition is satisfied.
Using recursion a long listing can be reduced to a few number of lines.
To understand recursion, we are taking recursive version of factorial function to find the factorial
of any given number.

5! = 5*4! = 5*24=120
4! = 4*3! = 4*6=24
3! = 3*2! = 3*2=6
2! = 2*1! = 2*1=2
1!=1

e.g. Recursive function


void func(int n)
{
if(n<=1)
return 1;
else
return(n+func(n-1));
} Manoj Kataria BKBIET, pilani
/*program using recurive function for factorial calculation*/ When recursion starts, the recursive
#include<stdio.h> function call does not execute immediately.
#include<conio.h> They are saved inside the stack with the
int fact(int); value of variable.
void main()
{ The items are “popped” out in reverse
int f,n; order in which they entered. This process
clrscr(); is called winding. The recussion stops
printf(“Enter number to find factorial:”); when n becomes 1 and function returns
scanf(“%d”,&n); value 1. The function call saved inside stack
f=fact(n); are popped out in reverse order and get
printf(“\nFactorial of %d is=%d”,n,f); executed.
}
Suppose n=5
/*recursive function*/ 5 * fact(4)
Int fact(int n) 5 * 4 * fact(3)
{ 5 * 4 * 3 * fact(2)
if(n==1) 5 * 4 * 3 * 2 * fact(1)
return 1; 5 * 4 * 3 * 2
else 5 * 4 * 6
return(n*fact(n-1)); 5 * 24
} 120
Manoj Kataria BKBIET, pilani
fact(1) POP
/*true*/
return 1
fact(2) fact(2) POP
/*false*/ /*false*/
return 2*fact(1) return 2*1
fact(3) fact(3) fact(3) POP
/*false*/ /*false*/ /*false*/
return 3*fact(2) return 3*fact(2) return 3*2
fact(4) fact(4) fact(4) fact(4) POP
/*false*/ /*false*/ /*false*/ /*false*/
return 4*fact(3) return 4*fact(3) return 4*fact(3) return 4*6
fact(5) fact(5) fact(5) fact(5) fact(5)
/*false*/ /*false*/ /*false*/ /*false*/ /*false*/ POP
return 5*fact(4) return 5*fact(4) return 5*fact(4) return 5*fact(4) return 5*24

f=fact(5) f=fact(5) f=fact(5) f=fact(5) f=fact(5) f=120


PUSH

main function Manoj Kataria BKBIET, pilani


Reversing List
Reversing list is an operation of stack, by using stack we can reverse the order of elements
of list.
Input : 3 2 1
Output : 1 2 3

Steps:
1. Traverse the list and push all elements of list on to stack
2. Traverse the list again and pop a value from top of stack and put them in reverse order

1 TOP 1
2 2
3 3
Push Pop
Infix to Postfix transformation
a+b -> infix expression
ab+ -> postfix expression (reverse polish notation)
+ab -> prefix expression (polish notation)
For evaluating an expression we know the concept of precedence and associativity. When an expression
contains more than one operator, the order in which the operators are evaluated depends on their precedence
and associativity (L->R or R->L)
If the precedence level is same then the order of evaluation depends on their associativity.
+ - / * -> L->R
++ -- -> R->L
Infix expressions are readable and solvable by humans. We can easily distinguish the order of operators and
can use the parenthesis to solve that part first during solving expression. The computer cannot differentiate
the operators and parenthesis easily that’s why postfix conversion is needed.
Difficulties in dealing with infix expression:
There is great deal of ambiguity in finding the value of infix expression.
e.g 10+8*6 = 58
(10+8)*6=108
To overcome this problem, expressions are evaluated by using one of the two forms: a). Postfix b). Prefix

The fundamental property of these two expressions is that the order in which the operations are performed
completely determined by the operators and operands in the expression.

Both the expression eliminates the need of parenthesis.

Infix Postfix Prefix


1. A + B*C A + BC* A + *BC
ABC*+ +A*BC

2. (A+B) * C AB+ *C +AB * C


AB+C* *+ABC

To convert infix expression into postfix we use STACK(holds operators during conversion).
The reason for using STACK is that it reverses the order of operators in the expression.

Manoj Kataria BKBIET, pilani


Algorithm (Infix to Postfix):
1. Push left parenthesis onto stack and add right parenthesis at the end of expression.
2. Scan the infix expression from Left-to-Right
3. If there is an operand, add it to P(Postfix expression)
4. If there is left parenthesis, Push it on to stack.
5. If an operator is encountered POP from stack every operator and add to P until stack does not empty.
Before adding to P make sure that the priority of current operator is less than or equal to the priority of
operator popped from stack.
6. If right parenthesis is encountered - repeatedly pop from stack and add to P until left parenthesis is
encountered.
Remove left parenthesis from stack.
7. Exit

( -> Left parenthesis ) -> Right parenthesis

*If an incoming operator has higher precedence than the operator on the top stack, push it on to stack
*If an incoming operator has lower or equal precedence than the operator on the top stack, pop from stack and
add to P and then push the incoming operator on to stack

Manoj Kataria BKBIET, pilani


e.g. convert infix to postfix A + B – ( C + D ) / E * F – ( G + H ) / K
Symbol scanned Stack P(Postfix Equivalent)
(
A ( A
+ (+ A
B (+ AB
- (- AB+
( (-( AB+
C (-( AB+C
+ (-(+ AB+C
D (-(+ AB+CD
) (- AB+CD+
/ (-/ AB+CD+
E (-/ AB+CD+E
* (-* AB+CD+ E/
F (-* AB+CD+E/F
- (- AB+CD+E/F*-
( (-( AB+CD+E/F*-
G (-( AB+CD+E/F*-G
+ (-(+ AB+CD+E/F*-G
H (-(+ AB+CD+E/F*-GH
) (- AB+CD+E/F*-GH+
/ (-/ AB+CD+E/F*-GH+
K (-/ Manoj Kataria BKBIET, pilani
AB+CD+E/F*-GH+K
) AB+CD+E/F*-GH+K/-
An infix expression is difficult to know and keep track of precedence of operators. Postfix expression itself
determines the precedence of operators (operators are placed in postfix expression depends upon its
precedence).

Convert the following infix expression into their postfix equivalent:


a). A * ( B + D ) / E – F * ( G + H / K )
b). ( A + ( B * ( C – D ) + E – ( F + G ) ) )

Manoj Kataria BKBIET, pilani


Arithmetic expression evaluation:
Using stack we not only convert the expression from infix notation to its postfix equivalent but we can also
evaluate postfix expression using stack.
It is convenient for compiler to evaluate an expression in its postfix form.
As in postfix expression there are no parenthesis and can be evaluated as two operands and operator, this
becomes easy for the compiler and computer to handle.

Algorithm:
1. Add ‘)’ right parenthesis to postfix expression
2. Read postfix expression from left to right until ‘)’ is encountered
3. If an operand is encountered PUSH it on to stack
4. If an operator is encountered, POP two elements
a). A is the top element
b). B is next to top
c). Evaluate B operator A (e.g. B + A)
PUSH result on to stack. (got to step2)
5. POP result from stack
6. END

Manoj Kataria BKBIET, pilani


e.g. Evaluate 2 3 * 4 5 ^ 4 / - )

Symbol Scanned Stack Result


2 2
3 2 , 3
* 6 2*3=6
4 6 , 4
5 6 , 4 ,5
^ 6 , 256 4 ^ 5 = 256
4 6 , 256 , 4
/ 6 , 64 256 / 4 = 64
- -58 6 – 64 = -58
) STACK empty -58
Result = -58
Evaluate the following postfix expression:
a). 5 4 6 + * 4 9 3 / + *
b). 7 5 2 + * 4 1 1 + / - Manoj Kataria BKBIET, pilani
Infix to Prefix conversion:
Steps:
1. Reverse the expression
2. Make every ‘)’ as ‘(‘ and vice versa
3. Convert expression to postfix form
4. Reverse the expression which is prefix equivalent

e.g. ( A + B ^ C ) * D + E ^ 5

1. Reverse the expression-> 5 ^ E + D * ) C ^ B + A (


2. Make every ‘(‘ as ‘)’ and ‘)’ as ‘(‘ -> 5 ^ E + D * ( C ^ B + A )
3. Convert expression to postfix form

Manoj Kataria BKBIET, pilani


Symbol scanned Stack Postfix form
(
5 ( 5
^ (^ 5
E (^ 5E
+ (+ 5E^
D (+ 5E^D
* (+* 5E^D
( (+*( 5E^D
C (+*( 5E^DC
^ (+*(^ 5E^DC
B (+*(^ 5E^DCB
+ (+*(+ 5E^DCB^
A (+*(+ 5E^DCB^A
) (+* 5E^DCB^A+
) 5E^DCB^A+*+
4. Reverse the resultant expression + * + A ^ B C D ^ E 5 (infix equivalent)
Manoj Kataria BKBIET, pilani
Tower of Hanoi:
Tower of Hanoi is a mathematical puzzle which consists of there tower (pegs) and more than one ring.
The rings are of different sizes and stacked upon in an ascending order i.e. the smaller one sits over the larger
one.
Tower count remains the same (i.e. three), when number of disks increase.

Disks

Tower A Tower B Tower C

Rules: our main aim is to move all disks from one tower to another tower without violating the sequence of
arrangement.
• Only one disk can be moved among tower at any given time
• Only the top disk can be removed
• No large disk can sit over a small disk.

Move all disk from tower A to tower C using tower B as auxiliary


Manoj Kataria BKBIET, pilani
Tower A Tower B Tower C Tower A Tower B Tower C
1 A to C

Tower B Tower A Tower B Tower C


Tower A Tower C
2 A to B 3 C to B

Tower A Tower B Tower C Tower A Tower B Tower C


A to C B to A
4 5

Tower A Tower B Tower C Tower A Tower B Tower C


6 B to C 7Manoj Kataria BKBIET, pilani A to C
Tower of Hanoi puzzle with n disks can be solved in minimum 2n-1 steps.
So with 3-disks : 23-1=7 steps

Steps:
1. Move (n-1) disks from source to auxiliary
2. Move nth disk from source to destination
3. Move (n-1) disks from auxiliary to destination

Move from A(source) to C(destination):


1. Move (n-1) disks from A to B
2. Move largest disk from A to C
3. Move (n-1) disks from B to C

For C implementation
Function : tower(n, beg, aux, end)

Manoj Kataria BKBIET, pilani


/*Program for Tower of Hanoi*/
#include<stdio.h>
#include<conio.h>
void tower(int, char, char, char);
void main()
{
int n;
char a=‘A’, b=‘B’, c=‘C’;
clrscr();
printf(“\nHow many disks:”);
scanf(“%d”,&n);
tower(n,a,b,c);
}
void tower(int n, char a, char b, char c)
{
if(n!=0)
{
tower(n-1,a,c,b);
printf(“\nMove from %c to %c’,a,c);
tower(n-1,b,a,c);
}
Manoj Kataria BKBIET, pilani
}
a=‘A’ b=‘B’ c=‘C’
tower(3,a,b,c)
Step 1: tower(2,a,c,b) tower(0,A,C,B,)
Step 2: move A->C Move A->C
tower(1,A,B,C) 1
Step 3: tower(2,b,a,c)
tower(0,C,B,A)
tower(2,A,C,B) Move A->B 2
tower(0,B,A,C)

tower(1,C,A,B) Move C->B 3


tower(3,A,B,C) Move A->C 4 tower(0,A,C,B)

tower(0,B,A,C)

tower(1,B,C,A) Move B->A 5

tower(0,A,C,B)
tower(2,B,A,C) Move B->C 6
tower(0,B,A,C)

tower(1,A,B,C) Move A->C 7

Manoj Kataria BKBIET, pilani tower(0,A,C,B)

You might also like