7 Stacks

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

Stacks

Overview

Stack
 A stack is a linear data structure or abstract data type for collection of items, with the
restriction that items can be added one at a time and can only be removed in the
reverse order in which they were added.
 The last item represents the top of the stack
 It is also known as LIFO (Last In First Out) or FILO(First In Last Out) data structure.

Example: Pile of plates, Pile of books etc.

TOP
Basic Operations

The common operations associated with a stack are as follows:


1. push: adds a new item on top of a stack.
2. pop: removes the item from the top of a stack
3. isEmpty: Check to see if the stack is empty
4. isFull: Check to see if stack is already full
5. returnTop: Indicate which item is at the top
Example

Insert Delete
ABCDE EDC

E TOP
D
C
B B TOP
A A
Implementation

Stack can be implemented in two ways –


1. Using array
2. Using linked list
Array as Stack

Create stack
C code: #define SIZE 10
struct stack{
int array[SIZE];
int TOP;
};

Initialize stack:
Algorithm Init_Stack (struct stack* STK): This algorithm initializes a stack with TOP = -1. Here,
STK is a pointer to a structure. TOP represents the index of the last item in a stack.
1. STK -> TOP = -1 // -1 means stack is empty
Illustration
SIZE = 8 Push 8, 56, 57, 7, 56, 9
0 1 2 3 4 5 6 7
5 8 56 57 7 56 9
TOP

Push 89, 90
7 8 56 57 7 56 9 89 90
TOP

Push 34 Stack Overflow

4 Times Pop
3 8 56 57 7

TOP
Push operation
Push operation

Below mentioned algorithm inserts an element into stack STK. Item is an element which is to
be inserted.

Algorithm Push(struct stack* STK, int Item)


1. If(STK -> TOP == (SIZE – 1)) \\ Check overflow condition
2. Display “Stack is full”
3. return
4. STK -> TOP = STK -> TOP + 1
5. STK -> array [STK ->TOP] = Item

Time Complexity = O(1)


Pop operation
Pop operation

This algorithm returns an element from stack TOP. Item is local variable.

Algorithm Pop(struct stack * STK)


1. If(STK -> TOP == – 1) \\ Check underflow condition
2. Display “Stack is empty”
3. Return
4. Item = STK -> array [STK ->TOP]
5. STK ->TOP = STK ->TOP - 1
6. Return Item
Time Complexity = O(1)
Printing Stack

This algorithm prints all the elements of stack.

Algorithm Print(struct stack * STK)


1. If(STK -> TOP == – 1) \\ Check underflow condition
2. Display “Stack is empty”
3. Return
4. For (i= STK ->TOP ; i>=0;i=i-1)
5. Printf (“%d \n”, STK -> array [i]);

Time Complexity = O(n)


Limitation

 Size of stack must be known in advance. However in real


scenario it is not possible.
 Stack growth should not restricted to finite number of
elements.
L i st
i n ked
L
as
S ta c k
Create stack

C code:
struct Node{
int INFO;
struct Node *NEXT;
};

Initialize stack:
Algorithm Init_LStack( struct Node *TOP): This algorithm initializes a stack by creating empty
linked list. TOP represents the last item of stack and pointing to empty linked list.

1. TOP = NULL // NULL means stack is empty


Illustration

Push 8, 56, 57

8 NULL
1. Push 8

TOP

2. Push 56 56 8 NULL

TOP

57 56 8 NULL
3. Push 57

TOP
Push operation

This algorithm inserts an element into stack by inserting as first node into linked list. Item is
element which is to be inserted. TOP is pointing to last inserted node i.e. first node of linked
list.

Algorithm Lpush(struct Node *TOP, int Item)


1. struct Node *New_Node
2. New_Node = Allocate memory
3. If(New_Node == NULL) \\ Check overflow condition
4. Display “Unable to allocate memory”
5. Exit //return
6. New_Node -> INFO = Item
7. New_Node ->NEXT = TOP
8. TOP = New_Node
Time Complexity = O(1)
Illustration

57 56 8 NULL

TOP
56 8 NULL
1. Pop

TOP
8 NULL
2. Pop

TOP

3. Pop TOP = NULL

4. Pop Underflow
Pop operation

This algorithm deletes and returns an element from stack TOP. Item is local variable.

1. Algorithm LPop(struct Node *TOP)


2. struct Node *Temp
3. Temp = TOP
4. If(TOP == NULL) \\ Check underflow condition
5. Display “Stack is empty”
6. Return NULL
7. Item = Temp ->INFO
8. TOP = Temp -> NEXT
9. Free Temp
10. Return Item

Time Complexity = O(1)


Print operation

Algorithm Print(struct Node *TOP ): This algorithm prints the stack

1. Node* Temp=TOP
2. While(Temp!=NULL)
3. printf(“%d\n”,Temp->INFO);
4. Temp=Temp->NEXT;

Time Complexity = O(n)


Applications

Stack is one of the most commonly used data structure.


 Calling Function –The most fundamental use of stacks relates to how functions
are called. One function can call another function which can call a third and so on.
When a call is made one method of passing arguments to a function is to push the
data onto the stack along with the address of the program statement where control
should return to after competition of function.
 Recursive Function – Function calls itself, the parameter, local variable status
return address where control is to be return are saved in stack.
 Expression Conversion : Infix to postfix, Infix to prefix etc.
 Arithmetic Expression Evaluation : postfix expression evaluation etc.
 Parentheses matching
 Tower of Hanoi
Arithmetic Expression Evaluation

Assume that given expression does not contain any unary operator.
For same level operations, precedence are performed from left to right.

Operations Precedence
Exponential (↑) 4
Multiplication (*) 3
Division (/) 3
Modulus (%) 3
Addition (+) 2
Subtraction (-) 2
Left Parenthesis 1
Right Parenthesis 1

NOTE: Higher the number higher the precedence.


Polish Notations

An arithmetic expression may be in the following forms –


1. Infix – Operator symbol is placed in between its two operands like X + Y

2. Prefix – Operator symbol is placed before its two operands like + X Y

3. Postfix – Operator symbol is placed after its two operands like X Y +

 In our usual practice, we solve the expressions in infix form.


 But, for computer program it is very complex to solve an expression in infix
form.
 Therefore, to evaluate arithmetic, first system converts it into prefix or postfix
form.
Expression Conversion

Following conversions are possible –


1. Infix to postfix
2. Infix to prefix
3. Postfix to infix
4. Prefix to infix
Infix to Postfix
Algorithm Infix_To_Post (InFix) – This algorithm takes infix expression and returns
equivalent postfix expression.

1. Create empty stack, say STK


2. While (!(InFix END))
3. pick an element from InFix and say it is Current
4. If (Current == left Parenthesis)
5. Push(STK, Current)
6. Else If (Current == right Parenthesis)
7. While (!(isEmpty(STK)) && STK -> array [STK ->TOP] != left
Parenthesis)
8. Operator = Pop(STK)
9. AppendTo(PostFix, Operator)
10. Pop(STK) // remove the left parenthesis and do
not append to PostFix
11. Else If(Current == Operand)
12. AppendTo(PostFix, Current)
13. Else If (Current == Operator)
14. While (!(isEmpty(STK)) && PREC(Current) <= PREC(STK->array[STK->TOP]))
15. Operator=Pop(STK)
16. AppendTo(PostFix, Operator)
17. Push(STK, Current)
18. Else
19. Display “Incorrect Expression”
20. Exit
21. While (!(isEmpty(STK)) && STK -> array [STK ->TOP] != left Parenthesis)
22. Operator = Pop(STK)
23. AppendTo(PostFix, Operator)
24. If (STK -> array [STK ->TOP] == left Parenthesis)
25. Display “Incorrect Expression”
26. Exit
Illustration
InFix Expression –
(A – B) * (C / D)
Current Character PostFix Expression Stack
( (
A A (
- A (-
B AB (-
) AB- Empty
* AB- *
( AB- *(
C AB–C *(
/ AB–C *(/
D AB–CD *(/
) AB–CD/ *
End of expression AB–CD/* Empty
Exercises

InFix Expression –
1. A+B*C-D/E
2. A*B-(C+D)+E
3. A + (B * C – (D / E ↑ F) * G) * H

PostFix Expression –
1. ABC*+DE/-
2. AB*CD+-E+
3. ABC*DEF↑/G*-H*+
Infix to Prefix
Algorithm Infix_To_Pre (InFix) – This algorithm takes infix expression and returns
equivalent prefix expression.

1. Create empty stack, say STK


2. RInFix = Reverse(InFix)
3. While (!(RInFix END))
4. pick an element from RInFix and say it is Current
5. If (Current == right Parenthesis)
6. Push(STK, Current)
7. Else If (Current == left Parenthesis)
8. While (!(isEmpty(STK)) && STK->array[STK->TOP] != right
Parenthesis)
9. Operator = Pop(STK)
10. AppendTo(PreFix, Operator)
11. Pop(STK) // remove the right parenthesis and do
not append to PreFix
12. Else If(Current == Operand)
13. AppendTo(PreFix, Current)
13. Else If (Current == Operator)
14. While (!(isEmpty(STK)) && PREC(Current) < PREC(STK->array[STK-
>TOP] )
15. Operator=Pop(STK)
16. AppendTo(PreFix, Operator)
17. Push(STK, Current)
18. Else
19. Display “Incorrect Expression”
20. Exit
21. While (!(isEmpty(STK)) && STK->array[STK->TOP] != right Parenthesis)
22. Operator = Pop(STK)
23. AppendTo(PreFix, Operator)
24. If (STK->array[STK->TOP] == right Parenthesis)
25. Display “Incorrect Expression”
26. Exit
27. PreFix = Reverse(PreFix)
28. Return Prefix
Illustration
InFix Expression – (A – B) * (C / D)
Reversed expression )D / C( * )B – A(
Current Character PreFix Expression Stack
) )
D D )
/ D )/
C DC )/
( DC/ Empty
* DC/ *
) DC/ *)
B DC/B *)
- DC/B *)-
A DC/BA *)-
Final PreFix
( DC/BA- *
*-AB/CD
End of Expression DC/BA-* Empty
Exercises

InFix Expression –
1. A+B*C-D/E
2. A*B-(C+D)+E
3. A + (B * C – (D / E ↑ F) * G) * H

PreFix Expression –
1. -+A*BC/DE
2. +-*AB+CDE
3. +A*-*BC*/D↑EFGH
Postfix to Infix Conversion
Algorithm Postfix_To_Infix (PostFix) – This algorithm takes postfix expression and
returns equivalent infix expression. In this case, we push and pop the strings. str1,
str2 are the temporary variables holding strings.

1. Create empty stack, say STK


2. While (!(PostFix END))
3. pick an element from PostFix and say it is Current
4. If(Current == Operator)
5. str2 = Pop(STK) // this becomes right operand
6. str1 = Pop(STK) //this becomes left operand
7. Concatenate str1, Current, and str2 // str=str1+ Current +str2
8. Enclose str with parenthesis
9. Push(STK, str)
10. Else
11. Push(STK, Current)
12. InFix = Pop(STK)
Postfix to Infix Conversion Illustration
PostFix Expression - ABC*DE/-+

C D
B B (B * C) (B * C)
A A A A A

E
D (D / E)
(B * C) (B * C) ((B * C) – (D / E)) (A + ((B * C) – (D / E)))
A A A

InFix Expression - (A + ((B * C)– (D / E)))


Evaluation of Postfix Expression

 We follow the same algorithm that converts Postfix to infix.


 Here, we compute each binary operation and then push the result into the stack.

Example –

23–1+43*+ = 12

3
2 2 – 3 = -1

3
1 4 4 12
-1 -1 0 0 0 0 12
Exercises

PostFix Infix

1. 9 9 * 81- ((9 * 9) – 81) = 0

2. 2 2 * 3 – ((2 * 2 ) – 3) = 1

3. 7 6 2 ^ * 4 / 8 - (((7 * (6 ^ 2)) / 4) – 8) = 55

PostFix Expression –
1. ABC*+DE/-
2. AB*CD+-E+
3. ABC*DEF↑/G*-H*+
Prefix to Infix Conversion
Algorithm Prefix_To_Infix (PreFix) – This algorithm takes prefix expression and
returns equivalent infix expression. In this case, we push and pop the strings. str1,
str2 are the temporary variables holding strings.

1. Create empty stack, say STK


2. RPreFix = Reverse (PreFix) // reverse
3. While (!(RPreFix END))
4. pick an element from PreFix and say it is Current
5. If(Current == Operator)
6. str1 = Pop(STK) //here str1 becomes left operand
7. str2 = Pop(STK) //here str2 becomes right operand
8. Concatenate str1, Current, and str2 // str=str1+ Current + str2
9. Enclose str with parenthesis
10. Push(STK, str)
11. Else
12. Push(STK, Current)
13. InFix = Pop(STK)
Prefix to Infix Conversion Illustration
PreFix Expression - *-AB/CD
Reversed Expression is DC/BA-*

A
B B
C (C / D)
(C / D) (C / D)
D D

(A – B)
(C / D) ((A – B) * (C/D))

InFix Expression - ((A – B) * (C / D))


Exercises

PreFix Expression –
1. -+A*BC/DE
2. +-*AB+CDE
3. +A*-*BC*/D↑EFGH
Evaluation of Prefix Expression

 We follow same algorithm that converts Prefix to infix.


 Here, we compute each binary operation and then push the result into the stack

Example –
Reverse
+-423 324-+

4 Infix:
2 4 - 2 =2 ((4 - 2) + 3) = 5
3

2
3 5
Exercises

PreFix Infix

1. - * 9 9 81 ((9 * 9) – 81) = 0

2. + + - 2 3 1 * 4 3 (((2 – 3) + 1) + ( 4 * 3)) =12


Parentheses matching
Algorithm Check_For_Balanced_Paranthesis (Exp) –Algorithm to check whether
given expression contains balanced parentheses.
1. Create empty stack, say STK
2. While (!(ExpEND))
3. pick an element from Exp and say it is Current
4. If( Current == ‘(‘ || Current == ‘{‘ ||Current == ‘[‘ )
5. Push(STK, Current)
6. Else if (Current == ‘)‘ || Current == ‘}‘ ||Current == ‘]‘ )
7. if (IsEmpty(STK) // stack is empty
8. Print “not balanced ”
9. Exit
10. X=Pop()
11. if (X is not a matching opening bracket ) // Eg. Current is ‘)’ & X is not ‘(‘
12. Print “not balanced ”
13. Exit
14. If (there is some opening brackets left in stack)// if stack is not empty
15. Print “not balanced ”
16. Else
17. Print “Balanced ”

You might also like