Dsa 5
Dsa 5
AND ALGORITHMS
1
Outline
■ Stack
■ Stack Implementation
– Array
– Linked List
■ Applications of Stack
2
INTRODUCTION ABOUT
STACKS
The stack is a very common data structure used in
programs which has lot of potential.
of the data.
Since many languages does not provide facility for stack, it is backed
Bottom
Stack
Example
Components of Stack
• Top is a variable which refers to
last position in stack.
STAC
K
PUSH POP
Add data to Take data
element in from element
stack. in stack
Kinds of Operation
contrary.
Full Operation
Push(Stack,8)
Push(Stack,3)
1 4 Push(Stack,5)
Push(Stack,1)
5 3
Push(Stack,7)
3 2 “Stack Overflow”
8 1
Top
Stack 0
Algorithm for Push Operation in Array
■ Push(s,data)
■ { If(top>=(max-1))
■ { cout<<“Stack Overflow”; }
■ Else
■ { top=top+1;
■ S[top]=data; }
18
Algorithm for Pop Operation in Array
■ Pop(s)
■ { If(top<0)
■ { cout<<“Stack underflow”; }
■ Else
■ { int x= s[top];
■ top=top-1;
■ Return x;}
19
Pop
■Steps in pop operation:
• Stack can be pop when its elements is not
empty.
head 8
❖ Push(Top,3) Top
head 3 8
Push
❖ Push(*Top,5)
Top
head 5 3 8
Pop
head Top
5 3 8
Pop
❖ Pop(*Top)
head Top
3 8
Pop
❖ Pop(*Top)
head Top
8
Algorithm for Push Operation in Linked list
■ Push(struct node *top, int info)
■ { Node *ptr=new node();
■ If(ptr==NULL)
■ { cout<<“Stack Overflow”; }
■ Elseif(top==NULL)
■ { Ptr->data= info;
■ Ptr->next=NULL;
■ Top=ptr; }
■ Else
■ { ptr->data= info;
■ Ptr->next=top;
■ Top=ptr;}
■ Return top;}
29
Algorithm for Pop Operation in Linked list
■ Pop(struct node *top)
■ { struct node *temp;
■ If(top==NULL)
■ { cout<<“Stack Underflow”; }
■ Else
■ {temp=top;
■ Top=top->next;
■ Delete(temp);}
■ Return top;}
30
STACK APPLICATIONS
Reverse a string
Evaluating Mathematical Expression
Compilers
Balancing Symbols
Stack Application
String is a b c d e f
PUSH to STACK
Reverse String...
Reversed String: f e d c b
a POP from STACK
Balancing Symbols
■ To check that every right brace, bracket, and parentheses must correspond to its left counterpart
– e.g. [( )] is legal, but [( ] ) is illegal
■ Algorithm
– Make an empty stack.
– Read characters until end of file
■ If the character is an opening symbol, push it onto the stack
■ If it is a closing symbol, then if the stack is empty, report an error
■ Otherwise, pop the stack. If the symbol popped is not the corresponding opening symbol, then
report an error
■ At end of file, if the stack is not empty, report an error
DSA- 06 35
Detecting Unbalanced Parenthesis
■ (
■ ((
■ (((
■ ((
■ (((
■ ((((
■ (((
■ ((
■ ( balanced
■
36
Balancing Symbols
DSA- 06
Solve
■ ([)]
■ ((()]))
38
39
40
41
42