Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit-III: Introduction To Stacks Applications of Stacks

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

Unit-III

 Introduction to stacks
 applications of stacks
Stack

• Stack is a Linear Data Structure which stores its


elements in an ordered manner or sequential order.
• Definition: A stack is an ordered list in which insertion
and deletion are done at one end, called top. The last
element inserted is the first one to be deleted. Hence,
it is called the Last in First out (LIFO) or First in Last out
(FILO) list.
• Stack maintains a pointer called top, which keeps track
of the top most element in the stack.
• Any insertions or deletions should be based upon the
value of top.
• Real time Examples
1.Pile of plates in cafeteria - The plates are added to the stack
as they are cleaned and they are placed on the top. When a plate,
is required it is taken from the top of the stack. The first plate
placed on the stack is the last one to be used.
2. Stack of coins
3. Stack of Books

Top of the Stack


Basic operations:
 The basic operations are insertion, deletion ,display.

 In stacks, special terms are given for insert and delete. i.e push
for insert and pop is for delete.

 Push: inserting or adding element into the stack is called push.

 Pop: deleting or removing element from the stack is


called pop.
Operations on Stack

• Two changes can be made to a stack.


they are,
1. Push – Inserting an element on to a
stack
2. Pop – Deleting or Removing an element from
the stack.
 Elements are inserted in the order as A,B,C,D,E
 It represents the stack of 5 elements.

 The top most element in the stack is E


 If we want to delete element E has to be deleted
first
 Pop operation- delete element from the stack
Example :-
ADT For
Stack
ADT for stack
int stack[5],top;

void push();
void pop();
void display();
int size();
void isEmpty();
void isFull();
Exceptions in
Stack
• Attemptin the execution of an operation
g may cause an error condition,
sometimes called an
exception. are said to be “thrown” by an operation
• Exceptions
that cannot be executed.
• In the Stack ADT, operations pop and top cannot
be performed if the stack is empty. The execution of
pop (or) top operation on an empty stack throws an
exception called as underflow.
• Trying to push an element in a full stack throws an
exception called as overflow.
Applications of stacks
 Balancing symbols
 Parenthesis matching.
 Evaluation of postfix expressions.
 Infix to prefix conversions.
 Infix to postfix conversions.
 Implementing function
calls(Recursion)
 Web browser history
 Undo operations in text editors
 Matching tags in HTML and XML
 Quick sort.
Implementing stack using arrays
Algorithm for inserting element into the stack:

Algorithm push()
1. if top=(SIZE-1)
then write (‘stack overflow’)
else
2. read item or data
3. top←top+1
4. stack[top]← item
5. stop
Explanation:
 The stack is of size max. This procedure inserts an element
item on to the top of a stack which is represented by an
array stack.
 The first step of this algorithm checks for an overflow
condition.
 Overflow means inserting element into a stack which is
full.
 If the top value reaches to maximum size of the stack then
elements cannot be inserted into the stack i.e. stack is full.
 Otherwise top is incremented by one and element is
inserted into the stack.
Algorithm to delete elements from the stack:

Algorithm pop()
1. if top=-1
then write (‘stack underflow’)
else
2. item ← stack[top]
3. top ← top-1
Explanation:
 This procedure deletes an element from the stack.

 The first step of this algorithm checks


for underflow condition.

 If the top value is -1 then stack is


empty.

 Empty stack is known as underflow.

 Takeout the element from the location where,


the top is pointing and then decrement top by
one.
Display of stack:
 Printing the contents of stack after push and pop
operations.
Algorithm print()
1. if top=-1
then write (‘stack empty’)
2. Repeat for i ← top to 0
print(stack[i])
3. stop
 Space complexity
 Time complexity of push(), pop(),size(), isEmpty(),
isFull()
will take O(1).
 Limitation in stack using array is that maximum size of
the
stack must be pre defined and it cannot be changed(fixed).
 When trying to add elements in the stack when the stack
is
full will rise the exception.
Representing Stack with Dynamic array

 Consider size of the stack is 4


 Insert following elements A,B,C,D

A B

A B C

A B C D
Stack is full when E is inserted create a new stack with double size
A B C D E and copy all the old stack elements to
new stack and named it as old stack
Representing Stack with Linked List

 Disadvantage of using an array to implement a stack or queue


is the wastage of space.

 Implementing stacks as linked lists provides a feasibility on


the number of nodes by dynamically growing stacks, as a
linked list is a dynamic data structure.

 The stack can grow or shrink as the program demands it to.

 A variable top always points to top element of the stack.

 top = NULL specifies stack is empty.


 In this representation, first node in the list is last
inserted element hence top must points to the first
element on the stack
 Last node in the list is the first inserted element in the
stack.
 Thus, push operation always adds the new element
at front of the list
 And pop operation removes the element at front
of the list.
 Size of the stack not required.
 Test for overflow is not applicable in this case.
Example:
The following list consists of five cells, each of which holds a data object
and a link to another cell.

 A variable, top, holds the address of the first cell in the list.

50 1500 110
0

40 1800 1500

30 1200 1800

20 1400 1200

top 10 NULL 1400


/* write a c program to implement stack using linked list */
#include<stdio.h #include<malloc.h> #include<stdlib.h> int
> int push(); pop(); int display();
int choice,i,item;
struct node {
int
data;
struct
node *link; top=NULL
}*top,
printf("\n***Select Menu***\n");
;
*new,*ptr;while(1) {
main() { printf("\n1.Push \n2.Pop \n3.Display \n4.Exit\n5.Count");
printf("\n\nEnter ur choice: ");
scanf("%d",&choice);
switch(choice) {
case 1: push(); break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
case 5: count(); break;
default: printf("\nWrong choice");
}/* end of switch */
}/* end of while */
}/* end of main */
int pop()
{
int push() if(top = = NULL)
{ {
new=malloc(sizeof(struct node)); printf("\n\nStack is empty");
printf("\nEnter the item: "); return;
scanf("%d",&item); }//if
new-
>data=item; else
if(top==NULL) {
{ prin
new- tf("\
>link= n\
NULL; nTh
} e
else dele
{ ted
new- ele
>link= me
top; nt
} is: %d",top->data);
top=new; top=top->link;
int display() int count()
{ {
ptr=top; int count=1;
if(top= =NULL) ptr=top;
{ if(top = =
printf("\nThe list is empty"); NULL)
return; {
} printf("\
printf("\nThe elements in the stact are: "); nThe list is
while(ptr!=NULL) empty");
{ re
printf("\n %d",ptr->data); tu
ptr=ptr->link; rn
}/* end of while */ ;
return; }
}/* end of display() */ while(ptr-
>link!
=NULL)
{
++count;
ptr=ptr->link;
Applications of stacks
 Balancing symbols ({},(),””)
 Evaluation of postfix expressions.
 Infix to postfix conversions.
 Infix to prefix conversions.
 Implementing function calls(Recursion)
 Web browser history
 Undo operations in text editors
 Matching tags in HTML and XML
 Quick sort.

S. Durga Devi ,CSE,CBIT


1.Parenthesis
matching
 The objective of this function is to check the
matching of parenthesis in an expression
i.e
 In an expression the no of left parenthesis must
be equal to no: of right parenthesis.

Ex: ((A+B)*C)
 This is a valid expression because in this no of
left parenthesis (2) = no: of right parenthesis (2).
Conversion of expressions
Arithmetic expressions can be represented in three ways:
 Infix notation
 Prefix notation
 Postfix notation
1.Infix notation- In which operator should be placed in between the two operands.
Example- A+B C-D E*F G/H.
2. Prefix notation (polish notation)-
•Operator preceded by the operand is called prefix notation
Examples
+AB -CD *EF \GH.
3. Postfix notation(reverse polish notation or suffix notation)-
•Operator should be placed after operands.
AB+ CD- EF* GH\
Notations – Conversions

Consider the infix expression: 2 + 3 * (5 – 7) / 9


Let us insert implicit parentheses
(2 + ((3 * (5 – 7)) / 9))

Transfer the operators to the beginning of


parentheses (+ 2 (/ (* 3 (– 5 7))
9))
Remove the parentheses: + 2 / * 3 – 5 79
This is the equivalent prefix expression.

Transfer the operators to the end of parentheses


(2 ((3 (5 7 –) *) 9 /) +)
Remove the parentheses: 2 3 5 7 – * 9 /
+ This is the equivalent postfix expression.
Examples
Infix Prefix Postfix
Expression Expression Expression

2 + 3 + 2 2 3 +
3
2 + 3 * 5 + 2 * 3 5 2 3 5 * +

(2 + 3) * 5 * + 2 3 5 2 3 + 5 *

– * 2 3 + 2 3 * 5 9 +
2 * 3 – (5 + 9)
5 9 –
Infix to post fix(RPN) Conversion
Algorithm to convert infix expression to postfix expression(RPN):
1. Declare a stack and postfix array(output : postfix expression)
2. Repeat the following steps until the end of the infix expression is reached.
1. Get input token (constant, variable, arithmetic
operator, left parenthesis, right parenthesis) in the infix
expression.
2. If the token is
1. A left parenthesis: Push it
onto the stack.
2. A right parenthesis:
1.Pop the stack elements and add to postfix array until a left
parenthesis is on the top of the stack.
2. Pop the left parenthesis also, but do not add to postfix
array
3. An operator:
1. While the stack is nonempty and token has lower or equal
priority than stack top element, pop and add to postfix array.
2. Push token onto the stack.
4. An operand: add to postfix
Note
• the lower precedence operator never placed
on top of the higher precedence.
• (A-B)*(D/E)
Operator Precedence
Infix expression- (A+B)^C-(D*E)/F
Infix Stack Post fix
( ( Empty
A ( A
+ (+ A
B (+ AB
) Empty AB+
^ ^ AB+
C ^ AB+C
- - AB+C^
( -( AB+C^
D -( AB+C^D
* -(* AB+C^D
E -(* AB+C^DE
) - AB+C^DE*
/ -/ AB+C^DE*
F -/ AB+C^DE*F
Empty AB+C^DE*F/-
Postfix (reverse polish notation) expression
evaluation
• Algorithm
1. Scan expression from left to right and repeat steps 2 and 3 for each
element of expression.
2.If an operand is encountered, push it on to stack.
3.If an operator op1 is encountered then
1. remove the top two elements of stack, where A is the top and B is the next
top element.
2. evaluate B op1 A
3. push the result back on to the stack.
4. set the top value on stack.
5. stop
Evaluate the expression
Postfix:- 5,6,2,+,*,12,4,/,-

Symbol stack content
scanned 5
5
5 6
6
5 6
2 2
+ 5 8
*
40
12 40 12
4 40 12 4
/ 40 3
- 40-3
37
Convert infix to postfix
1. expression
(A-B)*(D/E)
2. (A+B^D)/(E-F)+G
3. A*(B+D)/E-F*(G+H/K)
4. ((A+B)*D)^(E-F)
5. (A-B)/((D+E)*F)
6. ((A+B)/D)^((E-F)*G)
7. 12/(7-3)+2*(1+5)
8. 5+3^2-8/4*3+6
9. 6+2^3+9/3-4*5
10. 6+2^3^2-4*5
Evaluate the postfix expression
1. 5,3,+,2,*,6,9,7,-,/,-
2. 3,5,+,6,4,-,*,4,1,-,2,^,+
3. 3,1,+,2,^7,4,1,-,2,*,+,5.-

You might also like