0% found this document useful (0 votes)
28 views19 pages

Stacks

The document discusses stacks and their implementation using arrays and linked lists. It defines stacks, their operations like push and pop. It also discusses applications of stacks like conversion of infix to postfix notation, evaluation of postfix expressions and balancing of symbols.

Uploaded by

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

Stacks

The document discusses stacks and their implementation using arrays and linked lists. It defines stacks, their operations like push and pop. It also discusses applications of stacks like conversion of infix to postfix notation, evaluation of postfix expressions and balancing of symbols.

Uploaded by

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

STACKS

Unit-II: Stacks and Queues


Stacks: The Stack: Definition, operations, implementation using arrays, linked list and Stack
applications: Infix to postfix expression conversion, Evaluation of Postfix expressions,
balancing the symbols.Queue: definition, operations, implementation using arrays, linked
list&it’sApplications.Circular queue: definition&its operations, implementation, Dequeue:
definition & its types, implementation.

Learning Material
 Stack is a linear data structure.
 Stack can be defined as a collection of homogeneous elements, where insertion and
deletion operations takes place at only one end called TOP.
 The insertion operation is termed as PUSH and deletion operation is termed as POP
operation.
 The PUSH and POP operations are performed at TOP of the stack.
 An element in a stack is termed as ITEM.
 The maximum number of elements that stack can accommodate is termed as SIZE of
the stack.
 Stack Pointer ( SP ) always points to the top element of the stack.
 Stack follows LIFO principle. i.e. Last In First Out i.e. the element which is inserted
last into the stack will be deleted first from the stack.

Diagram of a stack

Stack Operations:- We can perform mainly 3 operations on stack.


1.Push :- Inserting an element into the stack
2.Pop:- Deleting an element from the stack
3.Peep:- Displaying top most element of the stack

Representation of stack
There are two ways of representation of a stack.
1. Array representation of a stack.
2. Linked List representation of a stack.
1. Array representation of a stack.
First we have to allocate memory for array.
Starting from the first location of the memory block, items of the stack can be stored in
sequential fashion.
Stack overflow
Trying to PUSH an item into full stack is known as Stack overflow.
Stack overflow condition is top = = SIZE - 1

Stack underflow
Trying to POP an item from empty stack is known as Stack underflow.
Stack underflow condition is top = = -1

Algorithm Stack_PUSH(item)
Input: item is new item to push into stack
Output: pushing new item into stack at top whenever stack is not full.
1. if(top == SIZE-1)
a) print(stack is full, not possible to perform push operation)
2. else
a) top=top+1
b) read item
c) s[top]=item

End Stack_PUSH

Algorithm Stack_POP( )
Input: Stack with some elements.
Output: item deleted at top most end.
1. if(top ==-1)
a) print(stack is empty not possible to pop)
2. else
a) item=s[top]
b) top=top-1
c) print(deleted item)

End Stack_POP
C Program to implement stack using arrays
#include<stdio.h>
#include<conio.h>
#define SIZE 5
void push( );
void pop( );
void peep( );
void display( );
int stack[10], top= -1, ele;
main( )
{
int ch;
clrscr( );
while(1)
{
printf("\nMENU");
printf("\n1.push \n2.pop \n3.peep \n4.display \n5.exit");
printf("\nEnter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1: push( );
break;
case 2: pop( );
break;
case 3: peep( );
break;
case 4: display( );
break;
default:exit( );
}
}
getch( );
}

void push( )
{
if( top==SIZE-1)
printf("\nStack is full");
else
{
top++;
printf("\nEnter the element to be inserted into the stack");
scanf("%d",&ele);
stack[top]=ele;
}
}

void pop( )
{
if( top==-1)
printf("\nStack is empty");
else
{
ele=stack[top];
printf("\nThe deleted element from the stack is %d",ele);
top--;
}
}

void peep( )
{
if( top == -1)
printf("\nStack is empty");
else
{
ele=stack[top];
printf("\nThe top most element of the stack is %d",ele);
}
}

void display( )
{
int i;
if( top==-1)
printf("\nStack is empty");
else
{
printf("\nThe elements of the stack are:\n");
for(i=top;i>=0;i--)
printf("%d\n",stack[i]);
}
}

2. Linked List representation of a stack

 The array representation of stack allows only fixed size of stack. i.e. static memory
allocation only.

 To overcome the static memory allocation problem, linked list representation of stack
is preferred.

 In linked list representation of stack, each node has two parts. One is data field is for
the item and link field points to next node.

 Empty stack condition is


tos = = NULL
 Full condition is not applicable for Linked List representation of stack. Because
here memory is dynamically allocated.
 In linked List representation of stack, top pointer always points to top most node only.
i.e. first node in the list.

Linked list representation of stack:-

C program to implement stacks using linked list:-


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *next;
}*tos,*new,*temp;
void push( );
void pop( );
void peep( );
void display( );
int ele;
main( )
{
int ch;
clrscr( );
while(1)
{
printf("\nMENU");
printf("\n1.push \n2.pop \n3.peep \n4.display \n5.exit");
printf("\nEnter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1: push( );
break;
case 2: pop( );
break;
case 3: peep( );
break;
case 4: display( );
break;
default:exit( );
}
}
getch( );
}

void push( )
{
new=(struct node *)malloc(sizeof(struct node));
printf("\nEnter an element to be inserted into the stack");
scanf("%d",&ele);
new->data=ele;
new->next=NULL;
if(tos==NULL)
tos=new;
else
{
new->next=tos;
tos=new;
}
}
void pop( )
{
if( tos==NULL)
printf("\nStack is empty");
else
{
temp=tos;
ele=tos->data;
printf("\nThe deleted element from the stack is %d",ele);
tos=tos->next;
temp->next=NULL;
}
}

void peep( )
{
if( tos==NULL)
printf("\nStack is empty");
else
{
ele=tos->data;
printf("\nThe top most element of the stack is %d",ele);
}
}

void display( )
{
if( tos==NULL)
printf("\nStack is empty");
else
{
printf("\nThe elements of the stack are:\n");
temp=tos;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
}
Arithmetic expressions or Algebraic expressions:-

An expression is a combination of operands and operators.

Eg. c= a + b

In the above expression a, b, c are operands and +, = are called as operators.

We have 3 notations for the expressions.

i. Infix notation
ii. Prefix notation
iii. Postfix notation
Infix notation: Here operator is present between two operands.
eg. a + b

The format for Infix notation as follows


<operand> <operator> <operand>

Prefix notation: Here operator is present before two operands.


eg. + a b

The format for Prefix notation as follows


<operator> <operand> <operand>

Postfix notation: Here operator is present after two operands.


eg. a b +

The format for Postfix notation as follows


<operand> <operand> <operator>

Applications of stack

1. Infix to postfix conversion


2. Evaluation of postfix expression
3. Balancing symbols or delimiter matching

1. Infix to postfix conversion

While conversion of infix expression to postfix expression, we must follow the precedence
(priority) of the operators.

Operator priority

( 0
+ - 1
*/% 2
^ or $ 3
To convert an infix expression to postfix expression, we can use one stack.
Within the stack, we place only operators and left parenthesis only. So stack used in
conversion of infix expression to postfix expression is called as operator stack.
Algorithm Conversion of infix to postfix

Input: Infix expression.

Output: Postfix expression.

1. Perform the following steps while reading of infix expression is not over
a) if symbol is left parenthesis then push symbol into stack.
b) if symbol is operand then add symbol to post fix expression.
c) if symbol is operator then check stack is empty or not.
i) if stack is empty then push the operator into stack.
ii) if stack is not empty then check priority of the operators.
(I) if priority of current operator > priority of operator present at top of
stack then push operator into stack.
(II) else if priority of operator present at top of stack >= priority of
current operator then pop the operator present at top of stack and add
popped operator to postfix expression (go to step I)
d) if symbol is right parenthesis then pop every element form stack up corresponding
left parenthesis and add the poped elements to postfix expression.
2. After completion of reading infix expression, if stack not empty then pop all the items from
stack and then add to post fix expression.
End conversion of infix to postfix
C Program to convert infix to postfix expression:-
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void push(char);
char pop();
int priority(char);
int top=-1;
char stack[20];
void main()
{
char postfix[30],infix[30],ch;
int i,j=0;
clrscr();
printf("\nEnter infix expression\n");
gets(infix);
for(i=0;infix[i]!='\0';i++)
{
ch=infix[i];
if(ch=='(')
push(ch);
else if(ch==')')
{
while( stack[top]!='(' && top!=-1)
{
postfix[j]=pop();
j++;
}
pop();
}
else if(isalpha(ch) || isdigit(ch))
{
postfix[j]=ch;
j++;
}
else
{
while(priority(ch)<=priority(stack[top]) && top!=-1)
{
postfix[j]=pop();
j++;
}
push(ch);
}
}
while(top!=-1)
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';
printf("\nresult is %s",postfix);
getch();
}
void push(char x)
{
top++;
stack[top]=x;
}
int pop()
{
return stack[top--];
}
int priority(char ch)
{
if(ch=='(')
return 0;
else if(ch=='+' || ch=='-')
return 1;
else if(ch=='*' || ch=='/' || ch=='%')
return 2;
else if(ch=='^')
return 3;
}
2.Evaluation of postfix expression
 To evaluate a postfix expression we use one stack.

 For Evaluation of postfix expression, in the stack we can store only operand. So stack
used in Evaluation of postfix expression is called as operand stack.
Algorithm PostfixExpressionEvaluation
Input: Postfix expression
Output: Result of Expression
1. Repeat the following steps while reading the postfix expression.
a) if the read symbol is operand, then push the symbol into stack.
b) if the read symbol is operator then pop the top most two items of the stack
and apply the operator on them, and then push back the result to the stack.

2. Finally stack has only one item, after completion of reading the postfix expression.
That item is the result of expression.
End PostfixExpressionEvaluation
C Program to evaluate postfix expression:-
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
int stack[20];
char postfix[20],ch;
void push(int);
int pop();
int top=-1;
main()
{
int i,op1,op2;
clrscr();
printf("\nenter postfix expression\n");
gets(postfix);
for(i=0;postfix[i]!='\0';i++)
{
ch=postfix[i];
if(isdigit(ch))
push(ch-48);
else
{
op2=pop();
op1=pop();
switch(ch)
{
case '+':push(op1+op2);break;
case '-':push(op1-op2);break;
case '*':push(op1*op2);break;
case '/':push(op1/op2);break;
case '%':push(op1%op2);break;
}
}
}
printf("\nThe result of postfix expression is %d",pop());
getch();
}
void push(int x)
{
top++;
stack[top]=x;
}
int pop()
{
return stack[top--];
}
3.Balancing Symbols or Delimiter matching :-

The objective of this application is to check the symbols such as parenthesis ( ) , braces { }
, brackets [ ] are matched or not.

Thus every left parenthesis, brace and bracket must have its right counterpart.

Algorithm for Balancing Symbols or Delimiter matching :-

1. Make an empty stack.

2. Read an expression from left to right.

3. If the reading character is opening symbol, then push it into stack.

4. If the reading character is closing symbol and if the stack is empty, then report as
unbalanced expression.

5. If the reading character is closing symbol and if the stack is not empty, then pop the
stack.

6. If the symbol popped is not the corresponding opening symbol, then report as
unbalanced expression.

7. After processing the entire expression and if the stack is not empty then report as
unbalanced expression.

8. After processing the entire expression and if the stack is empty then report as
balanced expression.

C program to implement balancing symbols or delimiter matching:-

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
void push(char);
char pop();
char stack[20];
int top=-1;
main()
{
char expr[20],ch;
int i;
clrscr();
printf("\nEnter an expression\n");
gets(expr);
for(i=0;expr[i]!='\0';i++)
{
ch=expr[i];
if(ch=='(' || ch=='{' || ch=='[')
push(ch);
else if(ch==')')
{
if(top==-1)
{
printf("\nUnbalanced expression");
exit();
}
else if( (ch=pop())!='(')
{
printf("\nUnbalanced expression");
exit();
}
}
else if(ch=='}')
{
if(top==-1)
{
printf("\nUnbalanced expression");
exit();
}
else if( (ch=pop())!='{')
{
printf("\nUnbalanced expression");
exit();
}
}
else if(ch==']')
{
if(top==-1)
{
printf("\nUnbalanced expression");
exit();
}
else if( (ch=pop())!='[')
{
printf("\nUnbalanced expression");
exit();
}
}
}
if(top==-1)
printf("\nBalanced expression");
getch();
}

void push(char x)
{
top++;
stack[top]=x;
}
int pop()
{
return stack[top--];
}

You might also like