SlideShare a Scribd company logo
1 of 28
Download to read offline
Stack(Last In First Out-LIFO)
8/24/2021 Mamta Bhattarai
Introduction
• A stack is an Abstract Data Type (ADT), commonly used in most
programming languages. It is named stack as it behaves like a real-
world stack, for example – a deck of cards or a pile of plates, etc.
• Stack is a sequential data structure in which insertion and deletion
takes place at one END call TOP.
8/24/2021 Mamta Bhattarai
Stack Representation
The following diagram depicts a stack and its operations −
8/24/2021 Mamta Bhattarai
Basic Operation
Stack operations may involve initializing the stack, using it and then de-initializing it. Apart
from these basic stuffs, a stack is used for the following two primary operations −
push() − Pushing (storing) an element on the stack.
pop() − Removing (accessing) an element from the stack.
When data is PUSHed onto stack.
To use a stack efficiently, we need to check the status of stack as well. For the same purpose,
the following functionality is added to stacks −
peek() − get the top data element of the stack, without removing it.
isFull() − check if stack is full.
isEmpty() − check if stack is empty.
8/24/2021 Mamta Bhattarai
Algorithms
• Algorithm of peek() function −
begin procedure peek
return stack[top](Top element )
end procedure
Implementation:
int peek()
{
return stack[top];
}
Algorithm of isfull() function −
begin procedure isfull
if top equals to MAXSIZE
return true
else
return false
endif
end procedure
Implementation:
bool isfull()
{
if (top== Maxsize-1)
return true;
else
return false;
}
8/24/2021 Mamta Bhattarai
Push Operation
• The process of inserting a new data element
onto stack is known as a Push Operation.
Push operation involves following steps −
• Step 1 − Checks if the stack is full.
• Step 2 − If the stack is full, display an error
and exit.
• Step 3 − If the stack is not full,
increments top to point next empty space.
• Step 4 − Adds data element to the stack
location, where top is pointing.
• Step 5 − stop
8/24/2021 Mamta Bhattarai
Algorithm for PUSH Operation
begin procedure push: stack, data
if stack is full
return null
endif
top ← top + 1
stack[top] ← data
end procedure
void push(int data) {
if(!isFull()) {
top = top + 1;
stack[top] = data;
}
else
{
printf("Could not insert data, Stack is full.n");
}
}
8/24/2021 Mamta Bhattarai
Pop Operation
• Deleting the item from the stack is called POP
operation.
• A Pop operation may involve the following steps
−
• Step 1 − Checks if the stack is empty.
• Step 2 − If the stack is empty, display error
message and exit.
• Step 3 − If the stack is not empty, accesses the
data element at which top is pointing.
• Step 4 − Decreases the value of top by 1.
• Step 5 − Returns success.
8/24/2021 Mamta Bhattarai
Algorithm for Pop Operation
• A simple algorithm
begin procedure pop:
stack
if stack is empty
return null
endif
data ← stack[top]
top ← top - 1
return data
end procedure
Implementation in C
int pop(int data) {
if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.n");
}
}
8/24/2021 Mamta Bhattarai
Notation
• The way to write arithmetic expression is known as a notation. An arithmetic
expression can be written in three different but equivalent notations, i.e.,
without changing the essence or output of an expression. These notations are −
• Infix Notation
• Prefix (Polish) Notation
• Postfix (Reverse-Polish) Notation
8/24/2021 Mamta Bhattarai
Infix Notation
• We write expression in infix notation, e.g. a - b + c, where operators
are used in-between operands. It is easy for humans to read, write,
and speak in infix notation but the same does not go well with
computing devices.
Prefix Notation
• In this notation, operator is prefixed to operands, i.e. operator is
written ahead of operands. For example, +ab. This is equivalent to its
infix notation a + b. Prefix notation is also known as Polish Notation.
Postfix Notation
• This notation style is known as Reversed Polish Notation. In this
notation style, the operator is postfixed to the operands i.e., the
operator is written after the operands. For example, ab+. This is
equivalent to its infix notation a + b.
8/24/2021 Mamta Bhattarai
8/24/2021 Mamta Bhattarai
Precedence and associativity
• Associativity describes the rule where operators with the same
precedence appear in an expression.
• Precedence and associativity determines the order of evaluation of an
expression. Following is an operator precedence and associativity
table (highest to lowest) −
8/24/2021 Mamta Bhattarai
Postfix Evaluation Algorithm
Evaluation of postfix notation
Algorithm
This algorithm finds the VALUE of an arithmetic expressions ‘P’ written in postfix notation.
Step 1: Add a right parenthesis “)” at the end of P
Step 2: Scan P from left to right and repeat step 3 and 4 for each element of P until the sentinel “)” is
encountered.
Step 3: If an operand is encountered, push it into stack.
Step 4: If an operator (ʘ) is encountered, then,
a. Remove the two top element of stack, where A is the top element and B is next to top element.
b. Evaluate B ʘ A.
c. Place the result of b. back on stack.
End of if structure
End of step 2 loop.
Step 5: Set VALUE = top element of stack.
Step 5: Exit or Stop
8/24/2021 Mamta Bhattarai
P:5,6,2,+,*,12,4,/,-
P:5,6,2,+,*,12,4,/,-,)
S.N0 Symbol
Scanned
Stack Evaluation
1 5 5
2 6 5,6
3 2 5,6,2
4 + 5,8 6+2=8
5 * 40 5*8=40
6 12 40,12
7 4 40,12,4
8 / 40,3 12/4=3
9 - 37 40-3=37
10 )
VALUE=37
8/24/2021 Mamta Bhattarai
Questions
• P:5,3,+,2,*,6,9,7,-,/,-
• P:3,5,+,6,4,-,*,4,1,-,2,^,+
• - * + 4 3 2 5
• ( - * + 4 3 2 5
8/24/2021 Mamta Bhattarai
Prefix Evaluation Algorithm
Evaluation of prefix notation
Algorithm
This algorithm finds the VALUE of an arithmetic expressions ‘P’ written in prefix notation.
Step 1: Add a left parenthesis “(” at the beginning of P
Step 2: Scan P from right to left and repeat step 3 and 4 for each element of P until the sentinel “(” is encountered.
Step 3: If an operand is encountered, push it into stack.
Step 4: If an operator (ʘ) is encountered, then,
a. Remove the two top element of stack, where A is the top element and B is next to top element.
b. Evaluate A ʘ B.
c. Place the result of b. back on stack.
End of if structure
End of step 2 loop.
Step 5: Set VALUE = top element of stack.
Step 5: Exit or Stop
8/24/2021 Mamta Bhattarai
Infix evaluation
• Approach: stack
• We will use two stacks
• Operand stack: This stack will be used to keep track of numbers.
• Operator stack: This stack will be used to keep operations (+, -, *, /, ^)
• Let’s define the Process: (will be used for the main algorithm)
• Pop-out two values from the operand stack, let’s say it is A(next to
top)and B(top).
• Pop-out operation from operator stack. let’s say it is ‘+’.
• Do A + B and push the result to the operand stack.
8/24/2021 Mamta Bhattarai
• Algorithm:(Infix evaluation)
• Scan one character at a time from left to right.
• If the character is an operand, push it to the operand stack.
• If the character is an operator,
• If the operator stack is empty then push it to the operator stack.
• Else If the operator stack is not empty,
• If the character’s precedence is greater than or equal to the precedence of the stack top of
the operator stack, then push the character to the operator stack.
• If the character’s precedence is less than the precedence of the stack top of the operator
stack then do Process (as explained) until character’s precedence is less or stack is not empty.
• If the character is “(“, then push it onto the operator stack.
• If the character is “)”, then do Process (as explained above) until the
corresponding “(” is encountered in operator stack. Now just pop out the
“(“.
• Once the expression iteration is completed and the operator stack is not
empty, do Process until the operator stack is empty. The VALUE left in the
operand stack is our final result.
8/24/2021 Mamta Bhattarai
Conversion Infix to postfix
Algorithm R-POLISH(Q,P)
Suppose ‘Q’ is an arithmetic expression written in infix notation, this algorithm
finds the equivalent postfix expression ‘P’.
Step 1: Push left parenthesis ‘(‘ onto the stack and right parenthesis ‘)’ to the end of
‘Q’.
Step 2: Scan ‘Q’ form left to right and repeat step 3 to 6 for each element of Q until
the stack is empty.
Step 3: If an operand is encountered, add it to P.
Step 4: If a left parenthesis is encountered push it onto stack.
Step 5: If an operator(O) is encountered, then (a) repeatedly pop from stack and
add it to P each operator (on the top of the stack) which has the same precedence
as or higher precedence then (O).
(b) Add operator to stack
[End of if structure]
8/24/2021 Mamta Bhattarai
To be continued
Step 6: If a right parenthesis is encountered then,
(a) Repeatedly pop from stack and add to P each operator until a left
parenthesis is encountered.
(b) Remove the left parenthesis [Do not add left parenthesis to P]
End of if structure
End of step 2 loop.
Step 7: Exit or Stop.
8/24/2021 Mamta Bhattarai
Q: A+(B*C-(D/E^F)*G)*H)
S.N Symbol
Scanned
Stack Expression
P
1 A ( A
2 + (+ A
3 ( (+( A
4 B (+( AB
5 * (+(* AB
6 C (+(* ABC
7 - (+(- ABC*
8 ( (+(-( ABC*
9 D (+(-( ABC*D
10 / (+(-(/ ABC*D
S.N Symbol
Scanned
Stack Expression P
11 E (+(-(/ ABC*DE
12 ^ (+(-(/^ ABC*DE
13 F (+(-(/^ ABC*DEF
14 ) (+(- ABC*DEF^/
15 * (+(-* ABC*DEF^/
16 G (+(-* ABC*DEF^/G
17 ) (+ ABC*DEF^/G*-
18 * (+* ABC*DEF^/G*-
19 H (+* ABC*DEF^/G*-H
20 ) ABC*DEF^/G*-H*+
8/24/2021 Mamta Bhattarai
• Questions:
(A-B)/(D+E)*F)
((A+B)/D^((E-F)*G))
8/24/2021 Mamta Bhattarai
Infix to prefix notation
Algorithm POLISH(Q,P)
Suppose ‘Q’ is an arithmetic expression written in infix notation, this algorithm finds the equivalent prefix
expression ‘P’.
Step 1: Push right parenthesis ‘)‘ onto the stack and left parenthesis ‘(’ to the end of ‘Q’.
Step 2: Scan ‘Q’ form right to left and repeat step 3 to 6 for each element of Q until the stack is empty.
Step 3: If an operand is encountered, add it to P.
Step 4: If a right parenthesis is encountered push it onto stack.
Step 5: If an operator(O) is encountered, then (a) repeatedly pop from stack and add it to P each operator (on
the top of the stack) which has the higher precedence then (O).
(b) Add operator to stack
[End of if structure]
Step 6: If a left parenthesis is encountered then,
(a) Repeatedly pop from stack and add to P each operator until a right parenthesis is encountered.
(b) Remove the right parenthesis [Do not add right parenthesis to P]
End of if structure
End of step 2 loop.
Step 7: Reverse P.
Step 8: Exit or Stop.
8/24/2021 Mamta Bhattarai
Q: (A+(B*C-(D/E^F)*G)*H
S.N Symbol
Scanned
Stack Expression P
1 H ) H
2 * )* H
3 ) )*) H
4 G )*) HG
5 * )*)* HG
6 ) )*)*) HG
7 F )*)*) HGF
8 ^ *)*)^ HGF
9 E )*)*)^ HGFE
10 / )*)*)/ HGFE^
S.N Symbol
Scanned
Stack Expression P
11 D )*)*)/ HGFE^D
12 ( )*)* HGFE^D/
13 - )*)- HGFE^D/*
14 C )*)- HGFE^D/*C
15 * )*)-* HGFE^D/*C
16 B )*)-* HGFE^D/*CB
17 ( )* HGFE^D/*CB*-
18 + )+ HGFE^D/*CB*-*
19 A )+ HGFE^D/*CB*-*A
20 ( HGFE^D/*CB*-*A+
+A*-*BC*/D^EFGH
8/24/2021 Mamta Bhattarai
Convert Postfix to Infix Expression
• Algorithm:
• Iterate the given expression from left to right, one character at a time
• If a character is operand, push it to stack.
• If a character is an operator,
• pop operand from the stack, say it’s A.
• pop operand from the stack, say it’s B.
• perform (B operator A) and push it to stack.
• Once the expression iteration is completed, initialize the result string
and pop out from the stack and add it to the result.
• Return the result.
8/24/2021 Mamta Bhattarai
1 Symbol Scanned Stack OPERATION
2 A A
3 B A,B
4 C A,B,C
5 - A,(B-C) (B-C)
6 + (A+(B+C)) (A+(B+C))
7 D (A+(B+C)),D
8 E (A+(B+C)),D,E
9 - (A+(B+C)), (D-E) (D-E)
10 F (A+(B+C)), (D-E),F
11 G (A+(B+C)), (D-E),F,G
12 - (A+(B+C)), (D-E),(F-G) (F-G)
13 H (A+(B+C)), (D-E),(F-G),H
14 + (A+(B+C)), (D-E), ((F-G)+H) ((F-G)+H)
15 / (A+(B+C)), ((D-E)/ ((F-G)+H)) ((D-E)/ ((F-G)+H))
16 * ((A+(B+C))* ((D-E)/ ((F-G)+H))) ((A+(B+C))* ((D-E)/ ((F-
G)+H)))
ABC-+DE-FG-
H+/*
8/24/2021 Mamta Bhattarai
Thank you
8/24/2021 Mamta Bhattarai

More Related Content

What's hot

What's hot (20)

Topdown parsing
Topdown parsingTopdown parsing
Topdown parsing
 
Parsing
ParsingParsing
Parsing
 
Lecture10 syntax analysis_6
Lecture10 syntax analysis_6Lecture10 syntax analysis_6
Lecture10 syntax analysis_6
 
Chapter 6 Intermediate Code Generation
Chapter 6   Intermediate Code GenerationChapter 6   Intermediate Code Generation
Chapter 6 Intermediate Code Generation
 
Parsing
ParsingParsing
Parsing
 
Lecture8 syntax analysis_4
Lecture8 syntax analysis_4Lecture8 syntax analysis_4
Lecture8 syntax analysis_4
 
Cs419 lec11 bottom-up parsing
Cs419 lec11   bottom-up parsingCs419 lec11   bottom-up parsing
Cs419 lec11 bottom-up parsing
 
COMPILER DESIGN- Syntax Analysis
COMPILER DESIGN- Syntax AnalysisCOMPILER DESIGN- Syntax Analysis
COMPILER DESIGN- Syntax Analysis
 
Predictive parser
Predictive parserPredictive parser
Predictive parser
 
Lecture7 syntax analysis_3
Lecture7 syntax analysis_3Lecture7 syntax analysis_3
Lecture7 syntax analysis_3
 
Nonrecursive predictive parsing
Nonrecursive predictive parsingNonrecursive predictive parsing
Nonrecursive predictive parsing
 
Types of Parser
Types of ParserTypes of Parser
Types of Parser
 
Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2Lecture 05 syntax analysis 2
Lecture 05 syntax analysis 2
 
Parsing
ParsingParsing
Parsing
 
CH4.pptx
CH4.pptxCH4.pptx
CH4.pptx
 
Top Down Parsing, Predictive Parsing
Top Down Parsing, Predictive ParsingTop Down Parsing, Predictive Parsing
Top Down Parsing, Predictive Parsing
 
Cd2 [autosaved]
Cd2 [autosaved]Cd2 [autosaved]
Cd2 [autosaved]
 
Parsing
ParsingParsing
Parsing
 
Topdown parsing
Topdown parsingTopdown parsing
Topdown parsing
 
Ch5a
Ch5aCh5a
Ch5a
 

Similar to Stack unit-ii

Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
chandankumar364348
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
haaamin01
 
The concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfThe concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdf
arihantsherwani
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
Kumar
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
KALPANAC20
 

Similar to Stack unit-ii (20)

Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptx
 
Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Stack in Data Structure
Stack in Data StructureStack in Data Structure
Stack in Data Structure
 
358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9358 33 powerpoint-slides_9-stacks-queues_chapter-9
358 33 powerpoint-slides_9-stacks-queues_chapter-9
 
Stacks
StacksStacks
Stacks
 
Lec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptxLec5-Stack-bukc-28022024-112316am (1) .pptx
Lec5-Stack-bukc-28022024-112316am (1) .pptx
 
The concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdfThe concept of stack is extremely important in computer science and .pdf
The concept of stack is extremely important in computer science and .pdf
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Data structure lecture7
Data structure lecture7Data structure lecture7
Data structure lecture7
 
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority QueueWhat is Stack, Its Operations, Queue, Circular Queue, Priority Queue
What is Stack, Its Operations, Queue, Circular Queue, Priority Queue
 
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptxApplication of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
 
Unit-ii-Queue ADT.pptx
Unit-ii-Queue ADT.pptxUnit-ii-Queue ADT.pptx
Unit-ii-Queue ADT.pptx
 
MO 2020 DS Stacks 3 AB.ppt
MO 2020 DS Stacks 3 AB.pptMO 2020 DS Stacks 3 AB.ppt
MO 2020 DS Stacks 3 AB.ppt
 
DS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptxDS UNIT1_STACKS.pptx
DS UNIT1_STACKS.pptx
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 
Infix-Postfix expression conversion
Infix-Postfix expression conversionInfix-Postfix expression conversion
Infix-Postfix expression conversion
 
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptxSTACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
STACK AND ITS OPERATIONS IN DATA STRUCTURES.pptx
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Stacks Data structure.pptx
Stacks Data structure.pptxStacks Data structure.pptx
Stacks Data structure.pptx
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 

Stack unit-ii

  • 1. Stack(Last In First Out-LIFO) 8/24/2021 Mamta Bhattarai
  • 2. Introduction • A stack is an Abstract Data Type (ADT), commonly used in most programming languages. It is named stack as it behaves like a real- world stack, for example – a deck of cards or a pile of plates, etc. • Stack is a sequential data structure in which insertion and deletion takes place at one END call TOP. 8/24/2021 Mamta Bhattarai
  • 3. Stack Representation The following diagram depicts a stack and its operations − 8/24/2021 Mamta Bhattarai
  • 4. Basic Operation Stack operations may involve initializing the stack, using it and then de-initializing it. Apart from these basic stuffs, a stack is used for the following two primary operations − push() − Pushing (storing) an element on the stack. pop() − Removing (accessing) an element from the stack. When data is PUSHed onto stack. To use a stack efficiently, we need to check the status of stack as well. For the same purpose, the following functionality is added to stacks − peek() − get the top data element of the stack, without removing it. isFull() − check if stack is full. isEmpty() − check if stack is empty. 8/24/2021 Mamta Bhattarai
  • 5. Algorithms • Algorithm of peek() function − begin procedure peek return stack[top](Top element ) end procedure Implementation: int peek() { return stack[top]; } Algorithm of isfull() function − begin procedure isfull if top equals to MAXSIZE return true else return false endif end procedure Implementation: bool isfull() { if (top== Maxsize-1) return true; else return false; } 8/24/2021 Mamta Bhattarai
  • 6. Push Operation • The process of inserting a new data element onto stack is known as a Push Operation. Push operation involves following steps − • Step 1 − Checks if the stack is full. • Step 2 − If the stack is full, display an error and exit. • Step 3 − If the stack is not full, increments top to point next empty space. • Step 4 − Adds data element to the stack location, where top is pointing. • Step 5 − stop 8/24/2021 Mamta Bhattarai
  • 7. Algorithm for PUSH Operation begin procedure push: stack, data if stack is full return null endif top ← top + 1 stack[top] ← data end procedure void push(int data) { if(!isFull()) { top = top + 1; stack[top] = data; } else { printf("Could not insert data, Stack is full.n"); } } 8/24/2021 Mamta Bhattarai
  • 8. Pop Operation • Deleting the item from the stack is called POP operation. • A Pop operation may involve the following steps − • Step 1 − Checks if the stack is empty. • Step 2 − If the stack is empty, display error message and exit. • Step 3 − If the stack is not empty, accesses the data element at which top is pointing. • Step 4 − Decreases the value of top by 1. • Step 5 − Returns success. 8/24/2021 Mamta Bhattarai
  • 9. Algorithm for Pop Operation • A simple algorithm begin procedure pop: stack if stack is empty return null endif data ← stack[top] top ← top - 1 return data end procedure Implementation in C int pop(int data) { if(!isempty()) { data = stack[top]; top = top - 1; return data; } else { printf("Could not retrieve data, Stack is empty.n"); } } 8/24/2021 Mamta Bhattarai
  • 10. Notation • The way to write arithmetic expression is known as a notation. An arithmetic expression can be written in three different but equivalent notations, i.e., without changing the essence or output of an expression. These notations are − • Infix Notation • Prefix (Polish) Notation • Postfix (Reverse-Polish) Notation 8/24/2021 Mamta Bhattarai
  • 11. Infix Notation • We write expression in infix notation, e.g. a - b + c, where operators are used in-between operands. It is easy for humans to read, write, and speak in infix notation but the same does not go well with computing devices. Prefix Notation • In this notation, operator is prefixed to operands, i.e. operator is written ahead of operands. For example, +ab. This is equivalent to its infix notation a + b. Prefix notation is also known as Polish Notation. Postfix Notation • This notation style is known as Reversed Polish Notation. In this notation style, the operator is postfixed to the operands i.e., the operator is written after the operands. For example, ab+. This is equivalent to its infix notation a + b. 8/24/2021 Mamta Bhattarai
  • 13. Precedence and associativity • Associativity describes the rule where operators with the same precedence appear in an expression. • Precedence and associativity determines the order of evaluation of an expression. Following is an operator precedence and associativity table (highest to lowest) − 8/24/2021 Mamta Bhattarai
  • 14. Postfix Evaluation Algorithm Evaluation of postfix notation Algorithm This algorithm finds the VALUE of an arithmetic expressions ‘P’ written in postfix notation. Step 1: Add a right parenthesis “)” at the end of P Step 2: Scan P from left to right and repeat step 3 and 4 for each element of P until the sentinel “)” is encountered. Step 3: If an operand is encountered, push it into stack. Step 4: If an operator (ʘ) is encountered, then, a. Remove the two top element of stack, where A is the top element and B is next to top element. b. Evaluate B ʘ A. c. Place the result of b. back on stack. End of if structure End of step 2 loop. Step 5: Set VALUE = top element of stack. Step 5: Exit or Stop 8/24/2021 Mamta Bhattarai
  • 15. P:5,6,2,+,*,12,4,/,- P:5,6,2,+,*,12,4,/,-,) S.N0 Symbol Scanned Stack Evaluation 1 5 5 2 6 5,6 3 2 5,6,2 4 + 5,8 6+2=8 5 * 40 5*8=40 6 12 40,12 7 4 40,12,4 8 / 40,3 12/4=3 9 - 37 40-3=37 10 ) VALUE=37 8/24/2021 Mamta Bhattarai
  • 16. Questions • P:5,3,+,2,*,6,9,7,-,/,- • P:3,5,+,6,4,-,*,4,1,-,2,^,+ • - * + 4 3 2 5 • ( - * + 4 3 2 5 8/24/2021 Mamta Bhattarai
  • 17. Prefix Evaluation Algorithm Evaluation of prefix notation Algorithm This algorithm finds the VALUE of an arithmetic expressions ‘P’ written in prefix notation. Step 1: Add a left parenthesis “(” at the beginning of P Step 2: Scan P from right to left and repeat step 3 and 4 for each element of P until the sentinel “(” is encountered. Step 3: If an operand is encountered, push it into stack. Step 4: If an operator (ʘ) is encountered, then, a. Remove the two top element of stack, where A is the top element and B is next to top element. b. Evaluate A ʘ B. c. Place the result of b. back on stack. End of if structure End of step 2 loop. Step 5: Set VALUE = top element of stack. Step 5: Exit or Stop 8/24/2021 Mamta Bhattarai
  • 18. Infix evaluation • Approach: stack • We will use two stacks • Operand stack: This stack will be used to keep track of numbers. • Operator stack: This stack will be used to keep operations (+, -, *, /, ^) • Let’s define the Process: (will be used for the main algorithm) • Pop-out two values from the operand stack, let’s say it is A(next to top)and B(top). • Pop-out operation from operator stack. let’s say it is ‘+’. • Do A + B and push the result to the operand stack. 8/24/2021 Mamta Bhattarai
  • 19. • Algorithm:(Infix evaluation) • Scan one character at a time from left to right. • If the character is an operand, push it to the operand stack. • If the character is an operator, • If the operator stack is empty then push it to the operator stack. • Else If the operator stack is not empty, • If the character’s precedence is greater than or equal to the precedence of the stack top of the operator stack, then push the character to the operator stack. • If the character’s precedence is less than the precedence of the stack top of the operator stack then do Process (as explained) until character’s precedence is less or stack is not empty. • If the character is “(“, then push it onto the operator stack. • If the character is “)”, then do Process (as explained above) until the corresponding “(” is encountered in operator stack. Now just pop out the “(“. • Once the expression iteration is completed and the operator stack is not empty, do Process until the operator stack is empty. The VALUE left in the operand stack is our final result. 8/24/2021 Mamta Bhattarai
  • 20. Conversion Infix to postfix Algorithm R-POLISH(Q,P) Suppose ‘Q’ is an arithmetic expression written in infix notation, this algorithm finds the equivalent postfix expression ‘P’. Step 1: Push left parenthesis ‘(‘ onto the stack and right parenthesis ‘)’ to the end of ‘Q’. Step 2: Scan ‘Q’ form left to right and repeat step 3 to 6 for each element of Q until the stack is empty. Step 3: If an operand is encountered, add it to P. Step 4: If a left parenthesis is encountered push it onto stack. Step 5: If an operator(O) is encountered, then (a) repeatedly pop from stack and add it to P each operator (on the top of the stack) which has the same precedence as or higher precedence then (O). (b) Add operator to stack [End of if structure] 8/24/2021 Mamta Bhattarai
  • 21. To be continued Step 6: If a right parenthesis is encountered then, (a) Repeatedly pop from stack and add to P each operator until a left parenthesis is encountered. (b) Remove the left parenthesis [Do not add left parenthesis to P] End of if structure End of step 2 loop. Step 7: Exit or Stop. 8/24/2021 Mamta Bhattarai
  • 22. Q: A+(B*C-(D/E^F)*G)*H) S.N Symbol Scanned Stack Expression P 1 A ( A 2 + (+ A 3 ( (+( A 4 B (+( AB 5 * (+(* AB 6 C (+(* ABC 7 - (+(- ABC* 8 ( (+(-( ABC* 9 D (+(-( ABC*D 10 / (+(-(/ ABC*D S.N Symbol Scanned Stack Expression P 11 E (+(-(/ ABC*DE 12 ^ (+(-(/^ ABC*DE 13 F (+(-(/^ ABC*DEF 14 ) (+(- ABC*DEF^/ 15 * (+(-* ABC*DEF^/ 16 G (+(-* ABC*DEF^/G 17 ) (+ ABC*DEF^/G*- 18 * (+* ABC*DEF^/G*- 19 H (+* ABC*DEF^/G*-H 20 ) ABC*DEF^/G*-H*+ 8/24/2021 Mamta Bhattarai
  • 24. Infix to prefix notation Algorithm POLISH(Q,P) Suppose ‘Q’ is an arithmetic expression written in infix notation, this algorithm finds the equivalent prefix expression ‘P’. Step 1: Push right parenthesis ‘)‘ onto the stack and left parenthesis ‘(’ to the end of ‘Q’. Step 2: Scan ‘Q’ form right to left and repeat step 3 to 6 for each element of Q until the stack is empty. Step 3: If an operand is encountered, add it to P. Step 4: If a right parenthesis is encountered push it onto stack. Step 5: If an operator(O) is encountered, then (a) repeatedly pop from stack and add it to P each operator (on the top of the stack) which has the higher precedence then (O). (b) Add operator to stack [End of if structure] Step 6: If a left parenthesis is encountered then, (a) Repeatedly pop from stack and add to P each operator until a right parenthesis is encountered. (b) Remove the right parenthesis [Do not add right parenthesis to P] End of if structure End of step 2 loop. Step 7: Reverse P. Step 8: Exit or Stop. 8/24/2021 Mamta Bhattarai
  • 25. Q: (A+(B*C-(D/E^F)*G)*H S.N Symbol Scanned Stack Expression P 1 H ) H 2 * )* H 3 ) )*) H 4 G )*) HG 5 * )*)* HG 6 ) )*)*) HG 7 F )*)*) HGF 8 ^ *)*)^ HGF 9 E )*)*)^ HGFE 10 / )*)*)/ HGFE^ S.N Symbol Scanned Stack Expression P 11 D )*)*)/ HGFE^D 12 ( )*)* HGFE^D/ 13 - )*)- HGFE^D/* 14 C )*)- HGFE^D/*C 15 * )*)-* HGFE^D/*C 16 B )*)-* HGFE^D/*CB 17 ( )* HGFE^D/*CB*- 18 + )+ HGFE^D/*CB*-* 19 A )+ HGFE^D/*CB*-*A 20 ( HGFE^D/*CB*-*A+ +A*-*BC*/D^EFGH 8/24/2021 Mamta Bhattarai
  • 26. Convert Postfix to Infix Expression • Algorithm: • Iterate the given expression from left to right, one character at a time • If a character is operand, push it to stack. • If a character is an operator, • pop operand from the stack, say it’s A. • pop operand from the stack, say it’s B. • perform (B operator A) and push it to stack. • Once the expression iteration is completed, initialize the result string and pop out from the stack and add it to the result. • Return the result. 8/24/2021 Mamta Bhattarai
  • 27. 1 Symbol Scanned Stack OPERATION 2 A A 3 B A,B 4 C A,B,C 5 - A,(B-C) (B-C) 6 + (A+(B+C)) (A+(B+C)) 7 D (A+(B+C)),D 8 E (A+(B+C)),D,E 9 - (A+(B+C)), (D-E) (D-E) 10 F (A+(B+C)), (D-E),F 11 G (A+(B+C)), (D-E),F,G 12 - (A+(B+C)), (D-E),(F-G) (F-G) 13 H (A+(B+C)), (D-E),(F-G),H 14 + (A+(B+C)), (D-E), ((F-G)+H) ((F-G)+H) 15 / (A+(B+C)), ((D-E)/ ((F-G)+H)) ((D-E)/ ((F-G)+H)) 16 * ((A+(B+C))* ((D-E)/ ((F-G)+H))) ((A+(B+C))* ((D-E)/ ((F- G)+H))) ABC-+DE-FG- H+/* 8/24/2021 Mamta Bhattarai