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

Stack Operations

The document provides a comprehensive overview of stack operations, including push, pop, peek, and evaluation of postfix expressions. It explains the principles of stack data structures, infix to postfix conversion, and includes code examples in C for implementing these functionalities. Additionally, it discusses the Tower of Hanoi puzzle and its solution method using recursion.

Uploaded by

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

Stack Operations

The document provides a comprehensive overview of stack operations, including push, pop, peek, and evaluation of postfix expressions. It explains the principles of stack data structures, infix to postfix conversion, and includes code examples in C for implementing these functionalities. Additionally, it discusses the Tower of Hanoi puzzle and its solution method using recursion.

Uploaded by

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

#include <stdio.

h>
int stack[100], i, j, choice=0, n, top=-1;
void push () {
int val;
if (top == n-1 )
printf("\n Overflow");
else {
printf("Enter the value?");
scanf("%d",&val);
top = top +1;
stack[top] = val;
}
}
void pop () {
int ele;
if(top == -1)
printf("Underflow");
else {
ele = stack[top];
void peek () {
if(top == -1)
printf("Underflow");
else
printf("Peeked element is %d\n", stack[top]);
}
void show() {
for (i=top;i>=0;i--)
printf("%d\n",stack[i]);
if(top == -1)
printf("Stack is empty");
}
int main () {
printf("Enter the number of elements in the stack ");
scanf("%d",&n);
printf("*********Stack operations using array*********");
printf("\n----------------------------------------------\n");
while(choice != 4) {
printf("Chose one from the below options...\n");
printf("\n1.Push\n 2.Pop\n 3.Show\n 4.Peek\n 5.Exit");
printf("\n Enter your choice \n");
scanf("%d", &choice);
switch(choice) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
show();
break;
case 4:
peek();
break;
case 5:
printf("Exiting....");
break;
default:
printf("Please Enter valid choice ");
};
}
return 0;
}
A stack is an ordered collection of items where the addition of new items
and the removal of existing items always take place at the same end.
This end is commonly referred to as the “top”. The working principle of
stack is LIFO [Last In First Out].
#include <stdio.h> #include <stdlib.h>
int top = -1;
int size;
int *stack=NULL;
void create();
void push();
int pop();
bool isEmpty();
bool isFull();
int main() {
printf("STATIC ARRAY (Total Capacity: %d)\n", N);
int choice;
while(1) {
printf("\n Choose any of the following options:\n");
printf(" 4: Check if the stack is empty 5: Check if the stack is full\n\
n");
scanf("%d", &choice);
switch(choice){
case 0: exit(0);
case 1: push(); break;
case 2: pop(); break;
case 3: peek(); break;
case 4: isEmpty(); break;
case 5: isFull(); break;
default: printf("Please choose a correct option!");
}
}
free(stack);
return 0;
}
void create() {
if(stack == NULL) {
printf(“Enter the size of stack\n”);
scanf(“%d”, &size);
stack=(int*)malloc(size*sizeof(int));
}
else
printf(“Already memory for stack is allocated”);
}
void push() {
if(top == N-1)
printf("Overflow State: can't add more elements into the stack\n");
else {
int x;
printf("Enter element to be pushed into the stack: ");
scanf("%d", &x);
top+=1;
*(stack+top) = x;
}
}
int pop() {
if(top == -1)
printf("Underflow State: Stack already empty, can't remove any element\
n");
else {
int x = *(stack+top);
printf("Popping %d out of the stack\n", x);
top-=1;
return x;
}
return -1;
}
int isEmpty() {
if(top == -1) {
printf("Stack is empty: Underflow State\n");
return 1;
}
printf("Stack is not empty\n");
return 0;
}
int isFull() {
if(top == N-1) {
printf("Stack is full: Overflow State\n");
return 1;
}
printf("Stack is not full\n");
return 0;
}
Infix to postfix conversion using stack
Scan all the symbols one by one from left to right in the given Infix
Expression.

If the reading symbol is an operand, then immediately append it to the


Postfix Expression.

If the reading symbol is left parenthesis ‘( ‘, then Push it onto the Stack.

If the reading symbol is right parenthesis ‘)’, then Pop all the contents
of the stack until the respective left parenthesis is popped and append each
popped symbol to Postfix Expression.

If the reading symbol is an operator (+, –, *, /), then Push it onto the
Stack. However, first, pop the operators which are already on the stack
that have higher or equal precedence than the current operator and append
them to the postfix. If an open parenthesis is there on top of the stack then
push the operator into the stack.
If the input is over, pop all the remaining symbols from the stack and
append them to the postfix.
Convert below infix expression to postfix expression using stack: (2-
3+4)*(5+6*7)
Infix Expression Stack Postfix Expression
(2-3+4)*(5+6*7) (
(2-3+4)*(5+6*7) ( 2
(2-3+4)*(5+6*7) (- 2
(2-3+4)*(5+6*7) (- 23
(2-3+4)*(5+6*7) (+ 23-
(2-3+4)*(5+6*7) (+ 23-4
(2-3+4)*(5+6*7) - 23-4+
(2-3+4)*(5+6*7) * 23-4+
(2-3+4)*(5+6*7) *( 23-4+
(2-3+4)*(5+6*7) *( 23-4+5
(2-3+4)*(5+6*7) *(+ 23-4+5
(2-3+4)*(5+6*7) *(+ 23-4+56
(2-3+4)*(5+6*7) *(+* 23-4+56
(2-3+4)*(5+6*7) *(+* 23-4+567
(2-3+4)*(5+6*7) * 23-4+567*+
Convert below infix expression to postfix expression using stack:
((A+B)-C*(D/E))+F
Infix Expression Stack Postfix Expression
((A+B)-C*(D/E))+F (
((A+B)-C*(D/E))+F ((
((A+B)-C*(D/E))+F (( A
((A+B)-C*(D/E))+F ((+ A
((A+B)-C*(D/E))+F ((+ AB
((A+B)-C*(D/E))+F ( AB+
((A+B)-C*(D/E))+F (- AB+
((A+B)-C*(D/E))+F (- AB+C
((A+B)-C*(D/E))+F (-* AB+C
((A+B)-C*(D/E))+F (-*( AB+C
((A+B)-C*(D/E))+F (-*( AB+CD
((A+B)-C*(D/E))+F (-*(/ AB+CD
((A+B)-C*(D/E))+F (-*(/ AB+CDE
((A+B)-C*(D/E))+F (-* AB+CDE/
((A+B)-C*(D/E))+F + AB+CDE/*-
((A+B)-C*(D/E))+F + AB+CDE/*-F
((A+B)-C*(D/E))+F AB+CDE/*-F+
Convert below infix expression to postfix expression using stack:
(a+b)*d+e/(f+a*d)+c
Infix Expression Stack Postfix Expression
(a+b)*d+e/(f+a*d)+c ( -
(a+b)*d+e/(f+a*d)+c ( a
(a+b)*d+e/(f+a*d)+c (+ a
(a+b)*d+e/(f+a*d)+c (+ ab
(a+b)*d+e/(f+a*d)+c - ab+
(a+b)*d+e/(f+a*d)+c * ab+
(a+b)*d+e/(f+a*d)+c * ab+d
(a+b)*d+e/(f+a*d)+c + ab+d*
(a+b)*d+e/(f+a*d)+c + ab+d*e
(a+b)*d+e/(f+a*d)+c +/ ab+d*e
(a+b)*d+e/(f+a*d)+c +/( ab+d*e
(a+b)*d+e/(f+a*d)+c +/( ab+d*ef
(a+b)*d+e/(f+a*d)+c +/(+ ab+d*ef
(a+b)*d+e/(f+a*d)+c +/(+ ab+d*efa
(a+b)*d+e/(f+a*d)+c +/(+* ab+d*efa
(a+b)*d+e/(f+a*d)+c +/(+* ab+d*efad
(a+b)*d+e/(f+a*d)+c +/ ab+d*efad*+
(a+b)*d+e/(f+a*d)+c + ab+d*efad*+/+
(a+b)*d+e/(f+a*d)+c + ab+d*efad*+/+c
(a+b)*d+e/(f+a*d)+c - ab+d*efad*+/+c+
Evaluate the given postfix expression using stack 623+-382/+*2$3+
The below diagram shows the evaluation of postfix expression using
stack. Kindly refer diagram from left to right and then below lines.

The final answer is 52.


Evaluate the given postfix expression using stack: 623+-382/+*
Evaluate the given postfix expression using stack: 23-4+567-+-
Ans: -1
Why postfix representation of the expression?
The compiler scans the expression either from left to right or from right
to left.
Consider the below expression: a op1 b op2 c op3 d
If op1 = +, op2 = *, op3 = +

 The compiler first scans the expression to evaluate the expression b *


c, then again scan the expression to add a to it. The result is then added
to d after another scan.

 The repeated scanning makes it very in-efficient. It is better to convert


the expression to postfix(or prefix) form before evaluation.

 The corresponding expression in postfix form is: abc*+d+. The postfix


expressions can be evaluated easily using a stack. We will cover postfix
expression evaluation in a separate post.
Algorithm:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
1 If the precedence of the scanned operator is greater than the
precedence of the operator in the stack(or the stack is empty or the stack
contains a ‘(‘ ), push it.
2 Else, Pop all the operators from the stack which are greater than or
equal to in precedence than that of the scanned operator. After doing that
Push the scanned operator to the stack. (If you encounter parenthesis
while popping then stop there and push the scanned operator in the
stack.)
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop the stack and and output it until
a ‘(‘ is encountered, and discard both the parenthesis.
6. Repeat steps 2-6 until infix expression is scanned.
7. Print the output
8. Pop and output from the stack until it is not empty.
#include <stdio.h> #include <ctype.h>
#define SIZE 50 /* Size of Stack */
char s[SIZE]; int top = -1; /* Global declarations */
/* Function for PUSH operation */
push(char elem) {
s[++top] = elem;
}
/* Function for POP operation */
char pop() {
return (s[top--]);
}
/* Function for precedence */
int pr(char elem) {
switch (elem) {
case '#': return 0; case '(': return 1;
case '+': case '-': return 2;
case '*': case '/' :
case '%' : return 3; case '^': return 4;
}
/* Main Program */
int main() {
char infx[50], pofx[50], ch, elem; int i = 0, k = 0;
printf("\n\nRead the Infix Expression ? "); scanf("%s", infx);
push('#');
while ((ch = infx[i++]) != '\0') {
if (ch == '(')
push(ch);
else if (isalnum(ch))
pofx[k++] = ch;
else if (ch == ')') {
while (s[top] != '(')
pofx[k++] = pop();
elem = pop(); /* Remove ( */
}
/* Operator */
else {
while (pr(s[top]) >= pr(ch))
push(ch);
}
}
while (s[top] != '#') /* Pop from stack till empty */
pofx[k++] = pop();
pofx[k] = '\0'; /* Make pofx as valid string */
printf("\n\nGiven Infix Expn: %s Postfix Expn: %s\n", infx, pofx);
return 0;
}
The Postfix notation is used to represent algebraic expressions. The
expressions written in postfix form are evaluated faster compared to
infix notation as parenthesis are not required in postfix.

Following is algorithm for evaluation postfix expressions:


1) Create a stack to store operands (or values).
2) Scan the given expression and do following for every scanned
element.
…..a) If the element is a number, push it into the stack
…..b) If the element is a operator, pop operands for the operator from
stack. Evaluate the operator and push the result back to the stack
3) When the expression is ended, the number in the stack is the final
answer.
#include<stdio.h>
#include<math.h>
int stack[20], top=-1;
void push(int x) {
stack[++top]=x;
}
int pop() {
return(stack[top--]);
}
int main() {
char s[20];
int x, i, y;
printf("evaluation of postfix\n");
printf("\nenter the postfix expression\n");
gets(s);
for(i=0;i<strlen(s);i++) {
if(isdigit(s[i]))
push(s[i]-'0');
y=pop();
x=pop();
switch(s[i]) {
case'+': push(x+y);
break;
case'-': push(x-y);
break;
case'*': push(x*y);
break;
case'/': push(x/y);
break;
case'^':
case'$': push(pow(x,y));
break;
}
}
}
printf("\n result is %d",pop());
return 0;
Tower of Hanoi is a mathematical puzzle. It consists of three poles and a
number of disks of different sizes which can slide onto any poles. The
puzzle starts with the disk in a neat stack in ascending order of size in one
pole, the smallest at the top thus making a conical shape. The objective of
the puzzle is to move all the disks from one pole (say ‘source pole’) to
another pole (say ‘destination pole’) with the help of the third pole (say
auxiliary pole).

The puzzle has the following two rules:


1. You can’t place a larger disk onto smaller disk
2. Only one disk can be moved at a time
Note: With three disks, the puzzle can be solved in seven moves. The
minimum number of moves required to solve a Tower of Hanoi puzzle
is 2n - , where n is the number of disks.

The pattern here is:


Shift 'n-1' disks from 'A' to 'B'.
Shift last disk from 'A' to 'C'.
Shift 'n-1' disks from 'B' to 'C'.
#include<stdio.h>
void tower(int n, int source, int temp,int destination) {
if(n == 0)
return;
tower(n-, source, destination, temp);
printf("\n Move disc %d from %c to %c", n, source, destination);
tower(n-, temp, source, destination);
}
int main() {
int n;
printf("\n Enter the number of discs: \n"); scanf("%d", &n);
tower(n, 'A', 'B', 'C');
printf("\n\n Total Number of moves are: %d", (int) pow(2,n)-1);
return 0;
}

You might also like