Stacks
Stack is a linear data structure in which in which insertion
and deletion is performed only at one end called the top of
stack.
(or)
Stack is a linear data structure in which a insertion of new
elements or deletion of existing element always takes at the
same end ,this end is called the top of the stack.
The elements are added and removed only from the
top of the stack.
Stack is based on working LIFO(Last in First Out)
Stacks are sometimes known as LIFO Lists (or) Push –
Down lists (or) FILO Lists(First In Last OUT).
Eg:- 1)A pile of plates in a canteen are ordered as
a stack.
2)A group of coins placed one on another is
also an example of stack.
Basic operations on stack:
1) Push(S,x):
Insertion or adding an element to stack.
2) Pop(S):
Deletion or removing an existing element from stack.
3) Peek(S):
Gives the element at the top of stack.
4)Display(S):
Display (or) Print the elements of the stack.
Basic terminology used in stacks:
1) Over flow:
It occurs when we try to insert or add more elements on
to a stack than it can hold.
2)Underflow:
It occurs when we try to delete or pop items when the
stack is empty.
Mechanism of Stack:
Push(20), Push(30), Push(10), pop(),pop(), Push(60),
Push(25),Pop().
Initially , top=-1;
Push(20) Push(30) Push(10) pop()
top= 10
top= 30 2
top=1 30
top= 20 1 30
20
0 20 20
pop() Push(60) Push(25) pop()
top= 25
top= 60 2
top=1 60
top= 20 1 60
20
0 20 20
Stack can be implemented by using
1) Array
2) Linked list
1) Implementing stacks using arrays:
#include<stdio.h>
#define MAX 10
int a[MAX],top=-1;
void push(int x);
int pop();
int peek();
void display();
int main()
{
intch,x;
while(1)
{
printf("\n1.Push\n2.Pop\n3.peek\n4.Display\n5.Exit\n");
printf("Enter the choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter the element to insert\n");
scanf("%d",&x);
push(x);
break;
case 2: x=pop();
if(x==-1)
printf("Stack underflown\n");
else
printf("The element popped=%d\n",x);
break;
case 3: x=peek();
printf("The element on top of stack=%d\n",x);
break;
case 4: printf("The elements in the stack are\n");
display();
break;
case 5:exit(0);
default:printf("Check the choice\n");
}
}
}
void push(int x)
{
if(top==MAX-1)
printf("Stack overflown\n");
else
{
a[++top]=x;
}
}
int pop()
{
int x;
if(top==-1)
return -1;
else
{
x=a[top--];
return x;
}
}
int peek()
{
retrun a[top];
}
void display()
{
int i;
if(top==-1)
printf("No element in stack\n");
else
{
for(i=top;i>=0;i--)
printf("%d\n",a[i]);
}
}
2) Implementing stacks using linked lists:
#include<stdio.h>
struct stack
{
int data;
struct stack *next;
};
typedefstruct stack node;
node *push(node *top,int x);
node *pop(node *top);
void display(node *top);
main()
{
intch,x;
node *head=NULL,*temp;
while(1)
{
printf("1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("Enter the choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter an element to insert\n");
scanf("%d",&x);
head=push(head,x);
break;
case 2:temp=head;
if(head==NULL)
printf("stack underflown\n");
else
printf("The element popped is %d\n",temp->data);
head=pop(head);
break;
case 3:display(head);
break;
case 4:exit(0);
}
}
}
node *push(node *top,int x)
{
node *new;
new=(node *)malloc(sizeof(node));
new->data=x;
new->next=NULL;
if(top==NULL)
top=new;
else
{
new->next=top;
top=new;
}
return top;
}
node *pop(node *top)
{
node *temp;
if(top==NULL)
return NULL;
else
{
temp=top;
top=top->next;
free(temp);
}
return top;
}
void display(node *top)
{
node *temp;
if(top==NULL)
printf("NO element in stack\n");
else
{
temp=top;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
}
Applications of stack:
1) To convert infix expression to postfix expression
2) To convert infix to prefix expression
3) To evaluate postfix expression
4) To check balancing symbols (or) parenthesis Matching
(or)delimiter matching
5) Using stack we implement graph search technique, Depth
First Search(DFS).
Conversion of infix to postfix expression:
Conversion of expressions:-
Arithmetic expressions can be represented in three ways they are
1) Infix Expression
The expression in which operators are written in
between their operands is called Infix expression.
Eg: (i) a+b
(ii) a*(b+c)/d
2) Prefix Expression
The expression in which operators are written before
their operands is called Infix expression.
Eg: (i) +ab
(ii) /*a+bcd
3) Postfix Expression
The expression in which operators are written after
their operands is called Infix expression.
Eg: (i) ab+
(ii) abc+*d/
Convert the following expressions to prefix and postfix
expressions.
Prefix ExpressionPostfix Expression
1) a+b*c +a*bc abc*+
2) (a+b)*c *+abc ab+c*
3) a*(b+c)/d /*a+bcd abc+*d/
4) a+b*c+(d+e+f)*g ++a*bc*++defg abc*+de+f+g*+
Operator precedence level Associativity
() 1 L to R
^(or) $ (or) exp 2 R to L
*, / ,% 3 L to R
+, - 4 L to R
Procedure to convert infix to postfix expression using
stack:
Given an input string as infix expression
Step 1: Scan the infix expression from left to Right taking one
character at a time till the end of the string.
Step 2: If the scanned character is an operand, insert it in postfix
string.
Step 3:
i) If the scanned character is an operator and stack top is having
left parentheses push the operator into the stack.
ii) If the scanned character is the right parentheses pop the
operators on the stack and place them in postfix string till left
parentheses is encountered in the stack. Discard both
parentheses.
iii) If the scanned character is an operator having higher
precedence than the stack top element then push the operator
on to the stack.
iv) If scanned character is an operator having lower precedence
or equal precedence than the stack top element, pop the
operator from the stack and place it on the postfix string, then
push the scanned operator in to the stack.
Step 3: When the end of the string is reached pop out all the
operators from the stack and insert them in the postfix string.
Step 4: Print the postfix string that contains both operands and
operators.
Program for conversion of infix to postfix expression:
#include<stdio.h>
#define MAX 10
char postfix[20],a[MAX];
int j=0,top=-1;
voidinfixtopostfix();
void push(char x);
char pop();
void precedence(char c);
int priority(char c);
main()
{
infixtopostfix();
}
voidinfixtopostfix()
{
char infix[20],c,x;
int i=0;
printf("Enter the infix expression\n");
scanf("%s",infix);
while(infix[i]!='\0')
{
c=infix[i];
if(isalpha(c)||isdigit(c))
{
postfix[j++]=c;
}
else
{
switch(c)
{
case '(':push(c);
break;
case '^':
case '*':
case '%':
case '/':
case '+':
case '-':precedence(c);
push(c);
break;
case ')':x=pop();
while(x!='(')
{
postfix[j++]=x;
x=pop();
}
break;
}
}
i++;
}
while(top!=-1)
{
postfix[j++]= pop();
}
postfix[j]='\0';
printf("The postfix expression of the given infix expression is %s\n",postfix);
}
void push(char x)
{
a[++top]=x;
}
char pop()
{
return a[top--];
}
void precedence(char c)
{
while(priority(c)<=priority(a[top]))
{
postfix[j++]=pop();
}
}
int priority(char c)
{
if(c=='^')
return 3;
else if(c=='*'||c=='%'||c=='/')
return 2;
else if(c=='+'||c=='-')
return 1;
else
return 0;
}
Evaluation of postfix expression:
Scan the postfix expression from left to right till operator is
encountered, then scan backwards to obtain immediate two left
operands. Perform the indicated operation on these operands
and then replace the operands and operators by the result and
repeat the above procedure until the postfix expression is
evaluated.
Eg:-
1) 632-5*+ = 615*+
=65+
=11
2) 6523+8*+3+* =6558*+3+*
=65 40 +3+*
=6 45 3+*
=6 48 *
=288
Evaluation of the postfix expression by using stack:
Step 1: Initially the operand stack is empty.
Step 2: Scan the postfix expression from left to right, take one
symbol at a time.
Step 3: If the symbol being scanned is an operand push it in to
the operand stack.
Step 4: Otherwise, (i.e if it is an operator) perform the following
operations:
Operand2= pop();
Operand1= pop();
Result =Operand1 operator Operand2;
Step 5: Push the Result into the operand stack and repeat the
steps 2, 3 and 4 above until end of the input.
Step 6: When we reach the end of postfix string, Pop the top
element of the operand stack, which is the result of the given
postfix expression.
Program for evaluation of postfix expression
#include<stdio.h>
int operation(int op1,int op2,char c);
void push(int x);
int pop();
# define MAX 5
int a[MAX],top=-1;
intmain()
{
char postfix[20],c;
int i=0,op1,op2,result;
printf("Enter the postfix expression\n");
scanf("%s",postfix);
while(postfix[i]!='\0')
{
c=postfix[i];
if(isdigit(c))
push(c-'0');
else
{
op2=pop();
op1=pop();
result=operation(op1,op2,c);
push(result);
}
i++;
}
printf("The result of the postfix expression=%d\n",a[top]);
}
int operation(int op1,int op2,char c)
{
switch(c)
{
case '^':return pow(op1,op2);
case '*':return (op1*op2);
case '%':return (op1%op2);
case '/':return (op1/op2);
case '+':return (op1+op2);
case '-':return (op1-op2);
}
}
void push(int x)
{
a[++top]=x;
}
int pop()
{
return a[top--];
}
Delimiter Matching (or) Parentheses matching :
Given an expression string exp, we want to check whether the pairs
and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.
Here we ensure that
Each opening on the left delimiter must be matched by a closing
(right) delimiter.
Left delimiters that occur later should be closed before those
occurring earlier.
Examples:
1) (c+(d+e)) -Correct
2) a+({b+[c+d]})-e -Correct
3) a+{b+(c+d}) -Not Correct , The ‘}’ after the d does
not match the ‘(‘ after the b.
4) a+{(b+c)}+e] -Not Correct, Nothing matches the ‘]’
which isafter e.
5) {a+(b+c) -Not Correct, Nothing matches the
opening ‘{‘.
Procedure to determine if the delimiters in an expression
match:
Step 1: Read the characters from the string.
Step 2: Whenever you see a left (opening) delimiter, push
it to the stack.
Step 3: Whenever you see a right (closing) delimiter, pop
the opening delimiter from the stack.
i) If you can’t pop the stack because it is empty, report a
missing left delimiter error.
ii) If they don’t match report a matching error.
Step 4: If the stack is non-empty after all the characters of
the expression have been processed report a
missing right delimiter matching.
Program to do delimiter matching
#include<stdio.h>
#define MAX 10
char a[MAX];
int top=-1;
void push(int x);
int pop();
main()
{
charexp[20],x,c;
int i=0,flag=1;
printf("Enter the expression\n");
scanf("%s",exp);
while(exp[i]!='\0')
{
c=exp[i];
if(c=='('||c=='['||c=='{')
{
push(c);
}
else if(c==')'||c==']'||c=='}')
{
if(top==-1)
{
flag=0;
break;
}
else
{
x=pop();
if(x=='('&&c==')'||x=='['&&c==']'||x=='{'&&c=='}')
{
flag=1;
}
else
{
flag=0;
break;
}
}
}
i++;
}
if(top!=-1)
flag=0;
if(flag==0)
printf("not matched");
else
printf("matched");
}
void push(char x)
{
a[++top]=x;
}
char pop()
{
return a[top--];
}
Conversion of infix to prefix expression using stack:
1. First we reverse the given infix expression.
2. Scan the characters one by one.
3. If the character is an operand, copy it to the prefix notation
output.
4. If the character is a closing parenthesis, then push it to the
stack.
5. If the character is an opening parenthesis, pop the elements
in the stack until we find the corresponding closing
parenthesis.
6. If the character scanned is an operator
If the operator has precedence greater than or equal to
the top of the stack, push the operator to the stack.
If the operator has precedence lesser than the top of the
stack, pop the operator and output it to the prefix notation
output and then check the above condition again with the
new top of the stack.
7. After all the characters are scanned, reverse the prefix
notation output.
Eg:
The prefix notation of the infix expression a/b-(c+d)-e is -
-/ab+cde.
Infix expression: a/b-(c+d)-e.
Reverse the infix expression: e-)d+c(-b/a
Convert it into postfix form using above procedure:
We get edc+ba/--
we reverse this postfix expression to get prefix expression :
- -/ab+cde.