1 / 14

Chapter 3

Chapter 3. Stacks. Chapter Objectives. To learn about the stack data type and how to use it To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list

omana
Download Presentation

Chapter 3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3 Stacks

  2. Chapter Objectives • To learn about the stack data type and how to use it • To understand how Java implements a stack • To learn how to implement a stack using an underlying array or linked list • To see how to use a stack to perform various applications, including finding palindromes, testing for balanced (properly nested) parentheses, and evaluating arithmetic expressions

  3. Stack Abstract Data Type Section 3.1

  4. A stack is one of the most commonly used data types. The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in first-out scheme (LIFO) Think of a spring-loaded pez dispenser Main stack operations: push(object): inserts an element object pop(): removes and returns the last inserted element Auxiliary stack operations: object peek(): returns the last inserted element without removing it integer size(): returns the number of elements stored booleanempty(): indicates whether no elements are stored The Stack ADT (§4.2)

  5. Stack Applications Section 3.2

  6. Balanced Parentheses • When analyzing arithmetic expressions, it is important to determine whether an expression is balanced with respect to parentheses ( a + b * ( c / ( d – e ) ) ) + ( d / e ) • The problem is further complicated if braces or brackets are used in conjunction with parentheses • The solution is to use stacks!

  7. Parentheses Matching • Each “(”, “{”, or “[” must be paired with a matching “)”, “}”, or “[” • correct: ( )(( )){([( )])} • correct: ((( )(( )){([( )])} • incorrect: )(( )){([( )])} • incorrect: ({[ ])} • incorrect: (

  8. Figure 6.2 Traces of the algorithm that checks for balanced braces

  9. Implementing a Stack Section 3.3

  10. Figure 6.4 An array-based implementation

  11. Figure 6.5 A reference-based implementation

  12. Additional Stack Applications Section 3.4

  13. Figure 6.7 The action of a postfix calculator when evaluating the expression 2 * (3 + 4)

  14. Figure 6.8 A trace of the algorithm that converts the infix expression a - (b + c * d)/e to postfix form

More Related