Professional Documents
Culture Documents
Module2 DSA
Module2 DSA
Module2 DSA
Stack
17/12/2023 2
Stack
• Linear data structure based on the LIFO principle
• To get to the bottom item, we must first remove all the items above it
• Elements can be added and removed only at one end(top of the
stack)
• Top item is always the first item to enter as well as leave the stack
• Can be implemented using array and linked list
Operations on Stacks
• push - place an item on the stack- function push(x)
Check whether stack is full i.e. overflow –function Boolean isFull()
• peek - Look at the item on top of the stack, but does not
remove it. function peek()
4
Implementing stack using
array
Algorithm for push and pop
• Push operation • Pop operation
• Step 1 − Check if the stack is full. • Step 1 − Check if the stack is empty.
• Step 2 − If the stack is full, then • Step 2 − If the stack is empty, then
display “overflow” and exit. display “underflow” and exit.
• Step 3 − If the stack is not full, • Step 3 − If the stack is not empty,
increment the top to point next access the data element at which
empty space. top is pointing.
• Step 4 − Add data element to the • Step 4 − Decrease the value of top
stack location, where top is by 1.
pointing. • Step 5 − Return success.
• Step 5 − Return success.
Push operation
• Overflow condition(if top=max-1) • Push(element)
• Step 1:If top==max-1 then
print overflow
end of if
• Step 2: Set top=top+1
• Step 3: Set stack[top]=element
• Step 4:end
Pop operation
• Underflow condition(if top=null) • Pop()
• Step 1:If top==null or -1 then
print underflow
end of if
• Step 2:set val=stack[top]
• Step 3:set top=top-1
• Return val
• Step 4:end
Peek operation
• Must check whether the stack is • Step 1:If top==null then
empty or contains some print stack is empty
elements.
• go to step 3
• Step 2:return stack[top]
• Step 3:end
C code to implement Stack(Menu driven program)
• Step 1 - Include all the header files which are used in the program and
define a constant 'SIZE' (size of input) with specific value.
• Step 2 - Declare all the functions used in stack implementation.
• Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
• Step 4 - Define an integer variable 'top' and initialize with '-1'. (int top = -
1)
• Step 5 - In main method, display menu with list of operations and make
suitable function calls to perform operation selected by the user on the
stack.
• Steps 1-4: Step 5:
void main()
• #include<stdio.h> {
int value, choice;
• #define SIZE 10 while(1){
printf(“\n1. Push\n2. Pop\n3.Peek\4. Display\n5. Exit");
• void push(int x); printf("\nEnter your choice: ");
scanf("%d",&choice);
• void pop(); switch(choice){
case 1: printf("Enter the value to insert: ");
• void peek(); scanf("%d",&value);
• void display(); push(value);
break;
• int stack[SIZE], case 2: pop();
break;
top = -1; case 3: peek();
break;
case 4:display();
break;
case 5: exit(0); default: printf("\nWrong
selection!!! Try again!!!");
}
}
Push function
• Push operation void push(int value)
Step 1 − Checks if the stack is full. {
Step 2 − If the stack is full, then display if(top == SIZE-1)
“overflow” and exit. printf("\nStack overflow");
Step 3 − If the stack is not full, else{
increment top to point next empty
top++;
space.
stack[top] = value;
Step 4 − Add data element to the stack
location, where top is pointing. printf("\nInsertion success!!!");
Step 5 − Returns success. }
}
Pop function
void pop()
• Pop operation
{
Step 1 − Checks if the stack is empty.
if(top == -1)
Step 2 − If the stack is empty, then
display “underflow” and exit. printf("\nStack underflow!!! ");
Step 3 − If the stack is not empty, access else
the data element at which top is {
pointing. printf("\nDeleted : %d", stack[top]);
Step 4 − Decrease the value of top by 1. top--;
Step 5 − Returns success. }
}
Peek/displaying top element
Step 1 - Check whether stack is EMPTY. (top == -1) void peek()
Step 2 - If it is EMPTY, then display "Stack is {
EMPTY!!!" and terminate the function.
Step 3 - If it is NOT EMPTY, then display top if(top == -1)
element of the stack. printf("\nStack is Empty!!!");
Step 4 - Return success else{
printf("%d\n",stack[top]);
}
}
displaying all the elements
Step 1 - Check whether stack is EMPTY. (top == -1) void display(){
Step 2 - If it is EMPTY, then display "Stack is if(top == -1)
EMPTY!!!" and terminate the function.
Step 3 - If it is NOT EMPTY, then define a variable printf("\nStack is Empty!!!");
'i' and initialize with top. Display stack[i] value and else{
decrement i value by one (i--).
int i;
Step 3 - Repeat above step until i value becomes
'0'. printf("\nStack elements are:\n");
for(i=top; i>=0; i--)
printf("%d\n",stack[i]);
}
}
Application of Stack
Applications of Stack
• Reversing a string
• Implementing parenthesis checker
• Evaluation of Arithmetic notations
• Polish notations
• Infix to postfix conversion
• Evaluation of a postfix expression
• infix to prefix conversion
• Evaluation of a prefix expression
• Recursion
• Tower of Hanoi
17
Reversing a string
• The idea is to create an empty stack and push all characters of the string into it.
Then pop each character one by one from the stack and put them back to the input
string starting from the 0'th index.
• Steps of Algorithm:
• Create an empty stack.
• One by one push all characters of string to stack(array).
• One by one pop all characters from stack and put them back to string.
Reversing a string
#include <stdio.h> void pop(){
#include <string.h> printf(“The character popped is %c",stack[top]);
#define SIZE 100 top=top-1
int top=-1;
}
Int stack[SIZE];
void main()
void push(char x){ {
if(top == SIZE-1){ char str[]="Krishna";
printf("stack overflow"); int len = strlen(str);
} int i;
else {
for(i=0;i<len;i++)
top=top+1
stack[top]=x; push(str[i]);
} } for(i=0;i<len;i++)
pop();
}
Application: Parenthesis matching
• Algorithmic steps:
• Initialize an empty stack. Set top pointer of stack to -1.
• Initialize the input expression as character array.
• Find length of input string and store it in an integer variable "length".
• Using a for loop, traverse input string from index 0 to length-1. Ignore everything you find other than the
opening and the closing parenthesis
• If the current character is a starting/opening bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
• Case 1: If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the
popped character is the matching starting bracket then fine else print “parenthesis mismatch”.
• Case 2: If stack is empty, then print “Expression is NOT BALANCED”, it means that the right
parenthesis are more than left parenthesis
• Case 3:After complete traversal, if there is some starting bracket left in stack it means left parenthesis
are more than right parenthesis then “Expression is NOT BALANCED”
Parenthesis matching
C program to check for balanced parenthesis
1 ( ( Push
2 ( (( Push
3 A (( A Print
4 + ((+ A Push
5 B ((+ AB Print
6 ) ( AB+ Pop
7 * (* AB+ Push
8 C (* AB+C Print
9 + (+ AB+C* Pop and push
10 ( (+( AB+C* Push
11 D (+( AB+C*D Print
12 * (+(* AB+C*D Push
13 E (+(* AB+C*DE Print
14 ) (+ AB+C*DE* Pop
15 ) AB+C*DE*+ Pop
Infix to prefix conversion
• Expression = (A+(B^C))*D+(E^5)
Step 1. Reverse the infix expression.
)5^E(+D*))C^B(+A(