Module2 DSA

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 29

Module 2

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()

• pop - remove an item from the stack- function pop()


Check whether stack is empty i.e. underflow –function Boolean isEmpty()

• 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

int check(char exp[] )


#include<stdio.h> { int i; char temp;
#include<string.h>
for(i=0;i<strlen(exp);i++) {
#include<stdlib.h>
if(exp[i]=='(' || exp[i]=='{' || exp[i]=='[')
#define MAX 30 push(exp[i]); //pushing the element
int top=-1;
if(exp[i]==')' || exp[i]=='}' || exp[i]==']')
int stack[MAX];
if(top==-1) /*stack empty*/ {
void push(char); printf("Right parentheses are more than left parentheses\n");
char pop(); return 0; }
int match(char a, char b);
int check(char []); else {
temp=pop();
int main() if(!match(temp, exp[i])) {
{ char exp[MAX];
printf("Mismatched parentheses are : ");
int valid;
printf("Enter an algebraic expression : "); printf("%c and %c\n",temp,exp[i]);
scanf("%s",exp); return 0;
valid=check(exp); } } }
if(valid==1)
printf("Valid expression\n"); if(top==-1) /*stack empty*/ {
else printf("Balanced Parentheses\n");
printf("Invalid expression\n"); return 1; }

return 0; else { printf("Left parentheses more than right arentheses\n");


} return 0; }}
C program to check for balanced parenthesis
void push(char item) {
if(top==(MAX-1)) {
int match(char a,char b) printf("Stack Overflow\n");
{ }
if(a=='[' && b==']') top=top+1;
stack[top]=item;
return 1;
}/*End of push()*/
if(a=='{' && b=='}')
char pop()
return 1; {
if(a=='(' && b==')') if(top==-1) {
return 1; printf("Stack Underflow\n");
else return 0; }
}/*End of match()*/ return(stack[top--]);
}/*End of pop()*/
Polish notations
• Way to write arithmetic expression
• Consists of operand ,Operator
• An algebraic expression can be represented using three different
notations.
• Infix e.g. (A + B) * (C - D)
• Prefix e.g. * + A B – C D polish notation
• postfix e.g. A B + C D - * reverse polish notation/suffix notation
• OPERATOR PRECEDENCE VALUE
• Exponentiation, parenthesis (highest)
• *, /, % (Next highest)
• +, - (Lowest)
Polish notations

sr.No Infix Notation Prefix Notation Postfix Notation


.
1 a+b +ab ab+

2 (a + b) ∗ c (+ab)*c = *+ab (ab+)*c = ab+c*

3 a ∗ (b + c) a*(+bc) = *a+bc a*(bc+) = abc+*

4 a/b+c/d (/ab)+(/cd)=+/ab/cd (ab/)+(cd/)=ab/cd/+

5 (a + b) ∗ (c + d) (+ab)*(+cd)=*+ab+cd (ab+)*(cd)+ = ab+cd+*

6 ((a + b) ∗ c) - d ((+ab)*c)-d = (*+abc)-d ((ab+)*c)-d = (ab+c*)-d


= -*+abcd = ab+c*d-
Infix to postfix conversion Algorithm
1. Create an empty Stack.
2. Input the infix expression. Scan the infix arithmetic expression from left to right.
•If the scanned character is an operand, append it to the end of the output list.
•If the scanned character is a left parenthesis, push it on the stack.
•If the scanned character is a right parenthesis, pop the stack until the corresponding left
parenthesis is removed, discard both the parenthesis(right as well as left). Append each
operator to the end of the output list.
•If the scanned character is an operator, *, /, +, or -, push it on the stack. However, first remove
any operators already on the stack that have higher or equal precedence and append them to
the output list.
3. Repeat step 2 until the infix expression is scanned.
4. Print the Stack output.
5. Pop and output all characters, including the operator, from the Stack until it is not empty.
we have infix expression (( A +B)*C+(D*E)) to convert into its equivalent postfix expression:

Sr No. Symbol Scanned Stack Expression Comment

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(

• Step 2. Make Every '(' as ')' and every ')' as '('


(5^E)+D*((C^B)+A)

• Step 3. Convert expression to postfix form(follow previous algorithm).


5E^DCB^A+*+
• Step 4. Reverse the expression.
+*+A^BCD^E5
Now, we have expression (5^E)+D*((C^B)+A) to convert into its equivalent postfix expression:

Sr No. Symbol Scanned Stack Expression Comment


1 ( ( Push
2 5 ( 5 Print
3 ^ (^ 5 Push
4 E (^ 5E Output
5 ) (^ 5E^ pop
6 + + 5E^ Push
7 D + 5E^D Print
8 * +* 5E^D Push
9 ( +*( 5E^D push
10 ( +*(( 5E^D push
11 C +*(( 5E^DC Print
12 ^ +*((^ 5E^DC Push
13 B +*((^ 5E^DCB Print
14 ) +*( 5E^DCB^ pop
15 + +*(+ 5E^DCB^ push
16 A +*(+ 5E^DCB^A print
17 ) +*(+ 5E^DCB^A+ pop
18 +* 5E^DCB^A+*+ pop

You might also like