SlideShare uma empresa Scribd logo
1 de 13
More About Stacks:
Stack Applications
Dan Nguyen
CS 146, Spring 2004
Professor Sin-Min Lee
Quick Introduction
• Stacks are linear lists.
• All deletions and insertions occur at one
end of the stack known as the TOP.
• Data going into the stack first, leaves out
last.
• Stacks are also known as LIFO data
structures (Last-In, First-Out).
Basic Stack Operations
• push – Adds an item to the top of a stack.
• pop – Removes an item from the top of
the stack and returns it to the user.
• stack top (top, peek) – Copies the top item
of the stack and returns it to the user; the
item is not removed, hence the stack is
not altered.
Additional Notes
• Stacks structures are usually implemented
using arrays or linked lists.
• For both implementations, the running
time is O(n).
• We will be examining common Stack
Applications.
Stack Applications
• Reversing Data: We can use stacks to reverse data.
(example: files, strings)
Very useful for finding palindromes.
Consider the following pseudocode:
1) read (data)
2) loop (data not EOF and stack not full)
1) push (data)
2) read (data)
3) Loop (while stack notEmpty)
1) pop (data)
2) print (data)
Stack Applications
• Converting Decimal to Binary: Consider the following pseudocode
1) Read (number)
2) Loop (number > 0)
1) digit = number modulo 2
2) print (digit)
3) number = number / 2
// from Data Structures by Gilbert and Forouzan
The problem with this code is that it will print the binary
number backwards. (ex: 19 becomes 11001000 instead of 00010011. )
To remedy this problem, instead of printing the digit right away, we can
push it onto the stack. Then after the number is done being converted, we
pop the digit out of the stack and print it.
Stack Applications
• Postponement: Evaluating arithmetic expressions.
• Prefix: + a b
• Infix: a + b (what we use in grammar school)
• Postfix: a b +
• In high level languages, infix notation cannot be used to
evaluate expressions. We must analyze the expression
to determine the order in which we evaluate it. A
common technique is to convert a infix notation into
postfix notation, then evaluating it.
Infix to Postfix Conversion
• Rules:
– Operands immediately go directly to output
– Operators are pushed into the stack (including parenthesis)
- Check to see if stack top operator is less than current operator
- If the top operator is less than, push the current operator onto stack
- If the top operator is greater than the current, pop top operator and
push onto stack, push current operator onto stack
- Priority 2: * /
- Priority 1: + -
- Priority 0: (
If we encounter a right parenthesis, pop from stack until we get
matching left parenthesis. Do not output parenthesis.
Infix to Postfix Example
A + B * C - D / E
Infix Stack(bot->top) Postfix
a) A + B * C - D / E
b) + B * C - D / E A
c) B * C - D / E + A
d) * C - D / E + A B
e) C - D / E + * A B
f) - D / E + * A B C
g) D / E + - A B C *
h) / E + - A B C * D
i) E + - / A B C * D
j) + - / A B C * D E
k) A B C * D E / - +
Infix to Postfix Example #2
A * B - ( C + D ) + E
Infix Stack(bot->top) Postfix
a) A * B - ( C - D ) + E empty empty
b) * B - ( C + D ) + E empty A
c) B - ( C + D ) + E * A
d) - ( C + D ) + E * A B
e) - ( C + D ) + E empty A B *
f) ( C + D ) + E - A B *
g) C + D ) + E - ( A B *
h) + D ) + E - ( A B * C
i) D ) + E - ( + A B * C
j) ) + E - ( + A B * C D
k) + E - A B * C D +
l) + E empty A B * C D + -
m) E + A B * C D + -
n) + A B * C D + - E
o) empty A B * C D + - E +
Postfix Evaulation
Operand: push
Operator: pop 2 operands, do the math, pop result
back onto stack
1 2 3 + *
Postfix Stack( bot -> top )
a) 1 2 3 + *
b) 2 3 + * 1
c) 3 + * 1 2
d) + * 1 2 3
e) * 1 5 // 5 from 2 + 3
f) 5 // 5 from 1 * 5
Backtracking
• Stacks can be used to backtrack to
achieve certain goals.
• Usually, we set up backtrack tokens to
indicate a backtrack opportunity.
References
• Our class textbook
• Data Structures: A Pseudocode Apporoach with C. Gilberg, Richard
F., Forouzan, Behrouz A.. PWS Publishing Company: 1998

Mais conteúdo relacionado

Mais procurados

Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTSoumen Santra
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure Janki Shah
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data StructureMeghaj Mallick
 
Asynchronous data transfer
Asynchronous data transferAsynchronous data transfer
Asynchronous data transferpriya Nithya
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structureghhgj jhgh
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm03446940736
 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queueRojan Pariyar
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSGokul Hari
 

Mais procurados (20)

Stack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADTStack and its Applications : Data Structures ADT
Stack and its Applications : Data Structures ADT
 
Stack using Array
Stack using ArrayStack using Array
Stack using Array
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Queues
QueuesQueues
Queues
 
single linked list
single linked listsingle linked list
single linked list
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
 
stack & queue
stack & queuestack & queue
stack & queue
 
Stack
StackStack
Stack
 
linked list
linked list linked list
linked list
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Stacks
StacksStacks
Stacks
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
Asynchronous data transfer
Asynchronous data transferAsynchronous data transfer
Asynchronous data transfer
 
Linked list
Linked listLinked list
Linked list
 
Stack
StackStack
Stack
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
Searching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And AlgorithmSearching techniques in Data Structure And Algorithm
Searching techniques in Data Structure And Algorithm
 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queue
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
Stack
StackStack
Stack
 

Destaque

Infix to-postfix examples
Infix to-postfix examplesInfix to-postfix examples
Infix to-postfix examplesmua99
 
Stack Implementation
Stack ImplementationStack Implementation
Stack ImplementationZidny Nafan
 
Infix to Prefix (Conversion, Evaluation, Code)
Infix to Prefix (Conversion, Evaluation, Code)Infix to Prefix (Conversion, Evaluation, Code)
Infix to Prefix (Conversion, Evaluation, Code)Ahmed Khateeb
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examplesgreatqadirgee4u
 
Conversion from infix to prefix using stack
Conversion from infix to prefix using stackConversion from infix to prefix using stack
Conversion from infix to prefix using stackHaqnawaz Ch
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and AlgorithmDhaval Kaneria
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTUREArchie Jamwal
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsAakash deep Singhal
 

Destaque (10)

Infix to-postfix examples
Infix to-postfix examplesInfix to-postfix examples
Infix to-postfix examples
 
Stack Implementation
Stack ImplementationStack Implementation
Stack Implementation
 
DS Q&A
DS Q&ADS Q&A
DS Q&A
 
Application of Stacks
Application of StacksApplication of Stacks
Application of Stacks
 
Infix to Prefix (Conversion, Evaluation, Code)
Infix to Prefix (Conversion, Evaluation, Code)Infix to Prefix (Conversion, Evaluation, Code)
Infix to Prefix (Conversion, Evaluation, Code)
 
Stacks Implementation and Examples
Stacks Implementation and ExamplesStacks Implementation and Examples
Stacks Implementation and Examples
 
Conversion from infix to prefix using stack
Conversion from infix to prefix using stackConversion from infix to prefix using stack
Conversion from infix to prefix using stack
 
Introduction to data structures and Algorithm
Introduction to data structures and AlgorithmIntroduction to data structures and Algorithm
Introduction to data structures and Algorithm
 
STACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURESTACKS IN DATASTRUCTURE
STACKS IN DATASTRUCTURE
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithms
 

Semelhante a Stack application

Semelhante a Stack application (20)

Stack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptxStack_Overview_Implementation_WithVode.pptx
Stack_Overview_Implementation_WithVode.pptx
 
Stack Operation In Data Structure
Stack Operation In Data Structure Stack Operation In Data Structure
Stack Operation In Data Structure
 
Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)Data structure and algorithm.(dsa)
Data structure and algorithm.(dsa)
 
Unit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptxUnit 3 Stacks and Queues.pptx
Unit 3 Stacks and Queues.pptx
 
Stack
StackStack
Stack
 
DS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptxDS MOD2 (1) (1).pptx
DS MOD2 (1) (1).pptx
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Prefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix NotationsPrefix, Infix and Post-fix Notations
Prefix, Infix and Post-fix Notations
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Stacks.ppt
Stacks.pptStacks.ppt
Stacks.ppt
 
Stack
StackStack
Stack
 
DS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptxDS-UNIT 3 FINAL.pptx
DS-UNIT 3 FINAL.pptx
 
5.-Stacks.pptx
5.-Stacks.pptx5.-Stacks.pptx
5.-Stacks.pptx
 
STACK1.pptx
STACK1.pptxSTACK1.pptx
STACK1.pptx
 
Chapter 6 ds
Chapter 6 dsChapter 6 ds
Chapter 6 ds
 
Data structures stacks
Data structures   stacksData structures   stacks
Data structures stacks
 
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
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Topic 2_revised.pptx
Topic 2_revised.pptxTopic 2_revised.pptx
Topic 2_revised.pptx
 
13 Stacks and Queues.pptx
13 Stacks and Queues.pptx13 Stacks and Queues.pptx
13 Stacks and Queues.pptx
 

Mais de Student

Cloud computing
Cloud computingCloud computing
Cloud computingStudent
 
Keyword research
Keyword researchKeyword research
Keyword researchStudent
 
Agile Process models
Agile Process modelsAgile Process models
Agile Process modelsStudent
 
Virtual technology
Virtual technologyVirtual technology
Virtual technologyStudent
 
Student management system
Student management systemStudent management system
Student management systemStudent
 
Ip services
Ip servicesIp services
Ip servicesStudent
 
Process models
Process modelsProcess models
Process modelsStudent
 
Student management system project report c++
Student management system project report c++Student management system project report c++
Student management system project report c++Student
 
Application layer chapter-9
Application layer chapter-9Application layer chapter-9
Application layer chapter-9Student
 
Database recovery
Database recoveryDatabase recovery
Database recoveryStudent
 
computer networks layers
computer networks layerscomputer networks layers
computer networks layersStudent
 
Uml struct2
Uml struct2Uml struct2
Uml struct2Student
 

Mais de Student (12)

Cloud computing
Cloud computingCloud computing
Cloud computing
 
Keyword research
Keyword researchKeyword research
Keyword research
 
Agile Process models
Agile Process modelsAgile Process models
Agile Process models
 
Virtual technology
Virtual technologyVirtual technology
Virtual technology
 
Student management system
Student management systemStudent management system
Student management system
 
Ip services
Ip servicesIp services
Ip services
 
Process models
Process modelsProcess models
Process models
 
Student management system project report c++
Student management system project report c++Student management system project report c++
Student management system project report c++
 
Application layer chapter-9
Application layer chapter-9Application layer chapter-9
Application layer chapter-9
 
Database recovery
Database recoveryDatabase recovery
Database recovery
 
computer networks layers
computer networks layerscomputer networks layers
computer networks layers
 
Uml struct2
Uml struct2Uml struct2
Uml struct2
 

Último

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 

Último (20)

Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Stack application

  • 1. More About Stacks: Stack Applications Dan Nguyen CS 146, Spring 2004 Professor Sin-Min Lee
  • 2. Quick Introduction • Stacks are linear lists. • All deletions and insertions occur at one end of the stack known as the TOP. • Data going into the stack first, leaves out last. • Stacks are also known as LIFO data structures (Last-In, First-Out).
  • 3. Basic Stack Operations • push – Adds an item to the top of a stack. • pop – Removes an item from the top of the stack and returns it to the user. • stack top (top, peek) – Copies the top item of the stack and returns it to the user; the item is not removed, hence the stack is not altered.
  • 4. Additional Notes • Stacks structures are usually implemented using arrays or linked lists. • For both implementations, the running time is O(n). • We will be examining common Stack Applications.
  • 5. Stack Applications • Reversing Data: We can use stacks to reverse data. (example: files, strings) Very useful for finding palindromes. Consider the following pseudocode: 1) read (data) 2) loop (data not EOF and stack not full) 1) push (data) 2) read (data) 3) Loop (while stack notEmpty) 1) pop (data) 2) print (data)
  • 6. Stack Applications • Converting Decimal to Binary: Consider the following pseudocode 1) Read (number) 2) Loop (number > 0) 1) digit = number modulo 2 2) print (digit) 3) number = number / 2 // from Data Structures by Gilbert and Forouzan The problem with this code is that it will print the binary number backwards. (ex: 19 becomes 11001000 instead of 00010011. ) To remedy this problem, instead of printing the digit right away, we can push it onto the stack. Then after the number is done being converted, we pop the digit out of the stack and print it.
  • 7. Stack Applications • Postponement: Evaluating arithmetic expressions. • Prefix: + a b • Infix: a + b (what we use in grammar school) • Postfix: a b + • In high level languages, infix notation cannot be used to evaluate expressions. We must analyze the expression to determine the order in which we evaluate it. A common technique is to convert a infix notation into postfix notation, then evaluating it.
  • 8. Infix to Postfix Conversion • Rules: – Operands immediately go directly to output – Operators are pushed into the stack (including parenthesis) - Check to see if stack top operator is less than current operator - If the top operator is less than, push the current operator onto stack - If the top operator is greater than the current, pop top operator and push onto stack, push current operator onto stack - Priority 2: * / - Priority 1: + - - Priority 0: ( If we encounter a right parenthesis, pop from stack until we get matching left parenthesis. Do not output parenthesis.
  • 9. Infix to Postfix Example A + B * C - D / E Infix Stack(bot->top) Postfix a) A + B * C - D / E b) + B * C - D / E A c) B * C - D / E + A d) * C - D / E + A B e) C - D / E + * A B f) - D / E + * A B C g) D / E + - A B C * h) / E + - A B C * D i) E + - / A B C * D j) + - / A B C * D E k) A B C * D E / - +
  • 10. Infix to Postfix Example #2 A * B - ( C + D ) + E Infix Stack(bot->top) Postfix a) A * B - ( C - D ) + E empty empty b) * B - ( C + D ) + E empty A c) B - ( C + D ) + E * A d) - ( C + D ) + E * A B e) - ( C + D ) + E empty A B * f) ( C + D ) + E - A B * g) C + D ) + E - ( A B * h) + D ) + E - ( A B * C i) D ) + E - ( + A B * C j) ) + E - ( + A B * C D k) + E - A B * C D + l) + E empty A B * C D + - m) E + A B * C D + - n) + A B * C D + - E o) empty A B * C D + - E +
  • 11. Postfix Evaulation Operand: push Operator: pop 2 operands, do the math, pop result back onto stack 1 2 3 + * Postfix Stack( bot -> top ) a) 1 2 3 + * b) 2 3 + * 1 c) 3 + * 1 2 d) + * 1 2 3 e) * 1 5 // 5 from 2 + 3 f) 5 // 5 from 1 * 5
  • 12. Backtracking • Stacks can be used to backtrack to achieve certain goals. • Usually, we set up backtrack tokens to indicate a backtrack opportunity.
  • 13. References • Our class textbook • Data Structures: A Pseudocode Apporoach with C. Gilberg, Richard F., Forouzan, Behrouz A.. PWS Publishing Company: 1998