DSU Unit 3 Stack
DSU Unit 3 Stack
3. STACK
An array is a random access data structure, where each element can be accessed
directly and in constant time. A typical illustration of random access is a book - each page of
the book can be open independently of others. Random access is critical to many algorithms,
for example binary search.
A linked list is a sequential access data structure, where each element can be accessed
only in particular order.
A stack is a basic data structure that can be logically thought as linear structure
represented by a real physical stack or pile, a structure where insertion and deletion of items
takes place at one end called top of the stack. The basic concept can be illustrated by thinking
of your data set as a stack of plates or books where you can only take the top item off the
stack in order to remove things from it.
Definition :- Stack is an ordered collection of elements where the addition and deletion of
existing element is always takes place at the same end called as top of the stack.
The basic implementation of a stack is also called a LIFO (Last In First Out) to
demonstrate the way it accesses data. There are basically three operations that can be
performed on stacks .They are
Stack as abstract data type :- stack can be defined as abstract data type. Stack of an element
of any particular type is finite sequence of that type together with following operations
1) Initialize stack
void push()
{
if(top==MAX-1)
printf("\n Stack is full");
else
{
printf("\n Enter the number:-:");
scanf("%d",&no);
top++;
stack[top]=no;
}
}
void pop()
{
if(top==-1)
printf("\n Stack is empty");
else
{
no=stack[top];
top--;
}
}
void display()
{
if(top==-1)
printf("\n Stack is empty");
else
{
for(i=top;i>=0;i--)
printf("\n %d",stack[i]);
}
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
int stack[MAX],top=-1,i=0,choice,no;
char ans;
void push();
void pop();
void display();
void push()
{
if(top==MAX-1)
printf("\n Stack is full");
else
{
printf("\n Enter the number:-:");
scanf("%d",&no);
top++;
stack[top]=no;
}
}
void pop()
{
if(top==-1)
printf("\n Stack is empty");
else
{
no=stack[top];
top--;
}
}
void display()
{
if(top==-1)
printf("\n Stack is empty");
else
{
for(i=top;i>=0;i--)
printf("\n %d",stack[i]);
}
}
void main()
{
clrscr();
do
{
printf("\n 1.PUSH");
printf("\n 2.POP");
printf("\n 3.DISPLAY");
printf("\n 4.EXIT");
printf("\n ENTER YOUR CHOICE");
scanf("%d", &choice);
switch(choice)
{
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\n Invalid choice");
break;
}
printf("\n do you want to continue [y/n]");
ans=getche();
}
while(ans=='Y'||ans=='y');
getch();
}
Applications of stack :-
1) Reverse of a string :-
One of the simple application of the stack is reverse of a string. It can simply be done
by pushing the individual characters of the string one by one on to the stack, till end
of string is reached and the elements of the stack are popped off.
For e.g. “REAL “
A
E A LA
R ↑
(POP A)
E E LAE
R ↑
(POP E)
R LAER
R ↑
(POP R)
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 10
char stack[MAX],str[10];
int top=-1,i=0,l=0;
void push(char);
char pop();
void push (char t1)
{
if(top==MAX-1)
{
printf("\n Stack is full");
}
else
{
top++;
stack[top]=t1;
}
}
char pop()
{
char t2;
if(top==-1)
{
printf("\n Stack is empty");
}
else
{
t2=stack[top];
top--;
}
return (t2);
}
void main()
{
clrscr();
printf("\n Enter String :-");
gets(str);
l=strlen(str);
printf("\n Length of string is %d:- ",l);
for(i=0;i<l;i++)
{
push(str[i]);
}
printf("\n Reverse of a string is :- ");
for(i=top;i>=0;i--)
{
char t2;
t2=pop();
printf("%c",t2);
}
getch();
}
2) Polish notations :-
The process of writing the operators of expressions either before or after their
operands is called as polish notation.
The computer system can understand and work only on binary paradigm. It assumes
that an arithmetic operations can be take place between two operands only. For e.g.
a*b ,f+g.d/h etc.
Usually arithmetic expression may contain more than two operators and operands. For
e.g. (a+b)*c*(d/e). This type of complex arithmetic expressions can be converted into
polish strings using stack.
There are basically 3 types of notations
a) Infix expression
b) Prefix expression
c) Postfix expression
a) Infix expression :- X+Y
Operators are written in-between their operands. This is the usual way we write
expressions. An expression such as A * ( B + C ) / D is usually taken to mean
something like: "First add B and C together, then multiply the result by A, then divide
by D to give the final answer."
Operator precedence :-
Exponential $ Highest
Multiplication / Division *, / Middle
Addition / Subtraction +,- Lowest
3) Recursion :-
Recursion is process of expressing functions in terms of itself. We can also define a
recursion is a process in which function calls itself with reduced input & has base
condition to stop i.e. the recursive function must satisfy two conditions
a) It must have termination condition
b) After each recursive call it should reach a value nearing to terminal condition.
#include<stdio.h>
#include<conio.h>
int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}
void main()
{
int n;
clrscr();
printf("\n Enter the number ");
scanf("%d",&n);
printf("\n Factorial of %d = %d",n,fact(n));
getch();
}
Output :-
Enter the number 5
Factorial of 5 = 120
#include<stdio.h>
#include<conio.h>
int multiply(int,int);
void main()
{
int a,b,product;
printf("\n Enter any two integers: ");
scanf("%d%d",&a,&b);
product = multiply(a,b);
printf("\n Multiplication of two integers is %d",product);
getch();
}
int multiply(int a,int b)
{
static int product=0,i=0;
if(i < a)
{
product = product + b;
i++;
multiply(a,b);
}
return product;
}
Output :-
#include<stdio.h>
#include<conio.h>
int Fibonacci(int);
void main()
{
int n, i = 0, c;
printf("\n Enter the last position for series ");
scanf("%d",&n);
printf("Fibonacci series\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
getch();
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
Output :-
9) After all the characters are read and the stack is not empty then pop the stack and add
the popped elements to postfix string
10) Stop
Example 1:- (A + B * C –D ) / ( E * F )
Example 2 :- (A * B + C / D ) * ( E + F $ G)
Example 3 :- A $ B * C – D + E / F / (G + H)
Example 4 :- ( A + ( B * C ) ) / ( C – (D * B ) )
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#define BLANK ' '
#define TAB '\t'
#define MAX 50
int main()
{
top=-1;
printf("Enter infix : ");
gets(infix);
infix_to_postfix();
printf("Postfix : %s\n",postfix);
getch();
return 1;
}
void infix_to_postfix()
{
unsigned int i,p=0;
char next;
char symbol;
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(!white_space(symbol))
{
switch(symbol)
{
case '(':
push(symbol);
break;
case ')':
while((next=pop())!='(')
postfix[p++] = next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
while( !isEmpty( ) && priority(stack[top])>=
priority(symbol) )
postfix[p++]=pop();
push(symbol);
break;
default: /*if an operand comes*/
postfix[p++]=symbol;
}
}
}
while(!isEmpty( ))
postfix[p++]=pop();
postfix[p]='\0'; /*End postfix with'\0' to make it a
string*/
}
stack[++top]=symbol;
}
for(i=0;i<strlen(postfix);i++)
{
if(postfix[i]<='9' && postfix[i]>='0')
push(postfix[i]-'0');
else
{
a=pop();
b=pop();
switch(postfix[i])
{
case '+':
temp=b+a; break;
case '-':
temp=b-a;break;
case '*':
temp=b*a;break;
case '/':
temp=b/a;break;
case '%':
temp=b%a;break;
case '^':
temp=pow(b,a);
}
push(temp);
}
}
result=pop();
return result;
}
Output :-
Enter infix : ( A + ( B * C ) ) / ( C – (D * B ) )
Postfix : A B C * + C D B * - /
Example :-123+*4-
Initially stack is empty . first three tokens are operands , so push them directly on
to the stack
Stack Expression
3
2
1
Next token is “+” which is operator. So pop two operands from the top of the
stack perform addition. The first popped element will be second operand and
second popped element will be first operand for the operation.
Stack Expression
2+3=5
The value of the expression is again pushed back into the stack
Stack Expression
5
1
Next scanned token is “*”, which is a operator. So pop two operands from the top
of the stack perform multiplication. The first popped element will be second
operand and second popped element will be first operand for the operation.
Stack Expression
1*5=5
The value of the expression is again pushed back into the stack
Stack Expression
Stack Expression
4
5
Next token is “-“, which is a operator. So pop two operands from the top of the
stack perform subtraction. The first popped element will be second operand and
second popped element will be first operand for the operation.
Stack Expression
5-4=1
The value of the expression is again pushed back into the stack
Stack Expression
Since all the tokens are scanned , the remaining element in the stack will be the
result of expression.
123+*4- = 1
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 50
int stack[MAX];
char post[MAX];
int top=-1;
void pushstack(int tmp);
void calculator(char c);
void main()
{
int i;
clrscr();
printf("Insert a postfix notation :: ");
gets(post);
for(i=0;i<strlen(post);i++)
{
if(post[i]>='0' && post[i]<='9')
{
pushstack(i);
}
if(post[i]=='+' || post[i]=='-' || post[i]=='*' ||
post[i]=='/' || post[i]=='^')
{
calculator(post[i]);
}
}
printf("\n\n Result :: %d",stack[top]);
getch();
}
void pushstack(int tmp)
{
top++;
stack[top]=(int)(post[tmp]-48);
}
void calculator(char c)
{
int a,b,ans;
a=stack[top];
stack[top]='\0';
top--;
b=stack[top];
stack[top]='\0';
top--;
switch(c)
{
case '+':
ans=b+a;
break;
case '-':
ans=b-a;
break;
case '*':
ans=b*a;
break;
case '/':
ans=b/a;
break;
case '^':
ans=b^a;
break;
default:
ans=0;
}
top++;
stack[top]=ans;
}
Output :-
Insert a postfix notation ::123+*4-
Result ::1
Example 1 :- 6 2 3 + - 3 8 2 / + * 2 $ 3 +
Example 2 :- 5 6 2 + * 12 4 / -
Example 3 :- 4 2 $ 3 * 3 – 8 4 / 1 1 + / +
4 2 $ 3 * 3 – 8 4 / 1 1 + / + = 46
Prefix notation places each operator before its operands. Steps for conversion of infix to
prefix expression are:-
Parenthesize the infix expression according to priority
Move each operator to its corresponding left parenthesis
Remove the parenthesis
( ( A + B ) / ( C – D ) )
Example 1 :- A $ B * C – D + E / F / ( G + G)
Example 2 :- ( ( A + B ) * ( C – D ) )
Example 3 :- ( A – B / C ) * ( D *E – F )
Example 4 :- ( A + ( B * C ) ) / ( C – ( D * B ) )
#include<stdio.h>
#include<conio.h>
#include<string.h>
#define MAX 20
char stack[MAX];
int top = -1;
char pop();
void push(char item);
case ')':
case '#':
return 1;
}
}
infix=strrev(infix);
stack[++top]='#';
for(i=0;i<strlen(infix);i++) {
symbol=infix[i];
if(isoperator(symbol)==0) {
prefix[j]=symbol;
j++;
}else {
if(symbol==')') {
push(symbol);
}else if(symbol=='(') {
while(stack[top]!=')') {
prefix[j]=pop();
j++;
}
pop();//pop out (.
}else {
if(prcd(symbol)>prcd(stack[top])) {
push(symbol);
}else {
while(prcd(symbol)<=prcd(stack[top])) {
prefix[j]=pop();
j++;
}
push(symbol);
}//end of else.
}//end of else.
}//end of else.
}//end of for.
while(stack[top]!='#') {
prefix[j]=pop();
j++;
}
prefix[j]='\0';//null terminate string.
prefix=strrev(prefix);
}
int main() {
char infix[20],prefix[20];
clrscr();
printf("Enter the valid infix string:\n");
gets(infix);
convertip(infix,prefix);
printf("The corresponding prefix string is:\n");
puts(prefix);
getch();
return 0;
}
char pop() {
char a;
a=stack[top];
top--;
return a;
}
Output :-
Enter the valid infix string: ( ( A + B ) * ( C – D ) )
Example :- + 2 * 3 + 4 5
Initially stack is empty. Scan from right to left .First two tokens are operands , so
push them directly on to the stack
Stack Expression
4
5
Next token is “+” which is operator. So pop two operands from the top of the
stack perform addition. The first popped element will be first operand and second
popped element will be second operand for the operation.
Stack Expression
4+5=9
The value of the expression is again pushed back into the stack
Stack Expression
3
9
Next scanned token is “*”, which is a operator. So pop two operands from the top
of the stack perform multiplication. The first popped element will be first operand
and second popped element will be second operand for the operation.
Stack Expression
3*9=27
The value of the expression is again pushed back into the stack
Stack Expression
27
Stack Expression
2
27
Next token is “+“, which is a operator. So pop two operands from the top of the
stack perform subtraction. The first popped element will be first operand and
second popped element will be second operand for the operation.
Stack Expression
2+27=29
The value of the expression is again pushed back into the stack
Stack Expression
29
Since all the tokens are scanned, the remaining element in the stack will be the
result of expression.
+ 2 * 3 + 4 5 = 29
Example 1 :- + - * + 1 2 / 4 2 1 $ 4 2
+ - * + 1 2 / 4 2 1 $ 4 2=21
Example 2 :- + - 2 7 * 8 / 12 4
+ - 2 7 * 8 / 12 4 = 19
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<math.h>
#define Max 20
int st[Max], top=-1;
int pop()
{
int ch;
if (top==-1)
{
printf("Stack is empty\n");
}
else
{
ch=st[top];
top--;
}
return ch;
}
void dispstack()
{
int k;
printf("stack Content: ");
for (k=top; k>=0; k--)
{
printf("%d, ", st[k]);
}
printf("\n");
}
char temp[25];
int i,val=0,ch1,ch2,j=0;
i=0; top=-1;
while (s[i]!='\0')
{
/*if operand is countered print it*/
if ( (s[i]>=48 && s[i]<=57) )
{
j=0;
temp[j]=s[i];
j++;
temp[j]='\0';
push(atoi(temp));
}
else
{
ch2=pop();
ch1=pop();
switch(s[i])
{
case '+' :
val=ch2+ch1;
break;
case '-' :
val=ch2-ch1;
break;
case '*' :
val=ch2*ch1;
break;
case '/' :
val=ch2/ch1;
break;
case '^' :
val=pow(ch2,ch1);
break;
}
push(val);
}
i++;
}
val=pop();
return val;
}
void main()
{
char s[25],s1[25];
int val;
clrscr();
printf("\n Enter a Prefix expression for evaluation\n");
scanf("%s",s);
strcpy(s1,strrev(s));
val= PreEval(s1);
printf("\n Value of Prefix Expression=%d\n", val);
getch();
}
Output :-