Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved. 0-13-140909-3 1 Stacks.

Slides:



Advertisements
Similar presentations
Lists Chapter 6 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Advertisements

Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks - 3 Nour El-Kadri CSI Evaluating arithmetic expressions Stack-based algorithms are used for syntactical analysis (parsing). For example.
Review of Stacks and Queues Dr. Yingwu Zhu. Our Focus Only link-list based implementation of Stack class Won’t talk about different implementations of.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
CS 240Chapter 6 - StacksPage 21 Chapter 6 Stacks The stack abstract data type is essentially a list using the LIFO (last-in-first-out) policy for adding.
Chapter 6: Stacks STACK APPLICATIONS STACK IMPLEMENTATIONS CS
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
Stack and Queue Dr. Bernard Chen Ph.D. University of Central Arkansas.
Infix, Postfix, Prefix.
Stacked Deque Gordon College Stacked Decks - get it?
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
Queues Chapter 8 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Chapter 8 stack ( 堆疊 ) Speaker: Lung-Sheng Chien Reference book: Larry Nyhoff, C++ an introduction to data structures.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Objectives of these slides:
Data Structures Using C++ 2E Chapter 7 Stacks. Data Structures Using C++ 2E2 Objectives Learn about stacks Examine various stack operations Learn how.
1 4. Stacks Introduction Consider the 4 problems on pp (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses.
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 Stacks.
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
Stack Applications.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
CSC 205 Programming II Postfix Expressions. Recap: Stack Stack features Orderly linear structure Access from one side only – top item Stack operations.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Stacks CHAPTER 7 MAY 21, 2015 Adapted from instructor resource slides Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
Searching: Binary Trees and Hash Tables CHAPTER 12 6/4/15 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education,
Adapted from instructor resources Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Exam Review 5/28/15. Software Development (Review)  Make it work…then make it pretty can result in dangerous code  Better to take a unified, consistent.
Chapter 18: Stacks and Queues
1 4. Stacks Introduction Consider the 4 problems on pp (1) Model the discard pile in a card game (2) Model a railroad switching yard (3) Parentheses.
For more notes and topics VISIT: IMPLEMENTATION OF STACKS eITnotes.com.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 19: Stacks and Queues (part 2)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
Review of Stacks and Queues Dr. Yingwu Zhu. How does a Stack Work? Last-in-First-out (LIFO) data structure Adding an item Push operation Removing an item.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
CHP-3 STACKS.
Chapter 17: Stacks and Queues. Objectives In this chapter, you will: – Learn about stacks – Examine various stack operations – Learn how to implement.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More Linking.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Lists Chapter.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Applications of Stack Maitrayee Mukerji. Stacks Last In First Out (LIFO List) ◦ FILO? Insertions and Deletions from the same end called the Top Push(),
CE 221 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - II Text: Read Weiss, §3.6 1Izmir University of Economics.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
Stacks Stacks.
Linked Lists Chapter 6 Section 6.4 – 6.6
Dr. Bernard Chen Ph.D. University of Central Arkansas
Queues Chapter 8 Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved
Copyright ©2012 by Pearson Education, Inc. All rights reserved
Stacks Chapter 4.
Data Structures – Week #3
Stack application: postponing data usage
Array Lists Chapter 6 Section 6.1 to 6.3
Data Structures – Week #3
Chapter 7 (continued) © 2011 Pearson Addison-Wesley. All rights reserved.
Presented by : Aman Gupta PGT CS KV No.1, Narimedu, Madurai
Presentation transcript:

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks Chapter 7

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Chapter Contents 7.1 Introduction to Stacks 7.2 Designing and Building a Stack Class – Array-Based 7.3 Linked Stacks 7.4 Use of Stacks in Function Calls 7.5 Case Study: Postfix (RPN) Notation (optional)

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Chapter Objectives Study a stack as an ADT Build a static-array-based implementation of stacks Build a dynamic-array-based implementation of stacks Build a linked-implementation of stacks Show how a run-time stack is used to store information during function calls (Optional) Study postfix notation and see how stacks are used to convert expressions from infix to postfix and how to evaluate postfix expressions

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction to Stacks Consider a card game with a discard pile –Discards always placed on the top of the pile –Players may retrieve a card only from the top We seek a way to represent and manipulate this in a computer program This is a stack What other examples can you think of that are modeled by a stack?

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Introduction to Stacks A stack is a last-in-first-out (LIFO) data structure Adding an item –Referred to as pushing it onto the stack Removing an item –Referred to as popping it from the stack

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved A Stack Definition: –An ordered collection of data items –Can be accessed at only one end (the top) Operations: –construct a stack (usually empty) –check if it is empty –Push: add an element to the top –Top: retrieve the top element –Pop:remove the top element

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Example Program Consider a program to do base conversion of a number (ten to two) Note program which assumes existence of a Stack class to accomplish this, Fig 7.2Fig 7.2 –Demonstrates push, pop, and top

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Selecting Storage Structure Model with an array –Let position 0 be top of stack Problem … consider pushing and popping –Requires much shifting

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Selecting Storage Structure A better approach is to let position 0 be the bottom of the stack Thus our design will include –An array to hold the stack elements –An integer to indicate the top of the stack Note beginning of Stack.h file, Fig. 7.3 Fig. 7.3 Note beginning of Stack.h file, Fig. 7.3 Fig. 7.3

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Implementing Operations Constructor –Compiler will handle allocation of memory Empty –Check if value of myTop == -1 Push (if myArray not full) –Increment myTop by 1 –Store value in myArray [myTop] Top –If stack not empty, return myArray[myTop] Pop –If array not empty, decrement myTop Output routine added for testing

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved The Stack Class The completed Stack.h file, Fig. 7.4AFig. 7.4A –All functions defined –Note use of typedef mechanism Implementation file, Stack.cpp, Fig 7.4BFig 7.4B Driver program to test the class, Fig 7.5Fig 7.5 –Creates stack of 4 elements –Demonstrates error checking for stack full, empty

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Dynamic Array to Store Stack Elements Same issues regarding static arrays for stacks as for lists –Can run out of space if stack set too small –Can waste space if stack set too large As before, we demonstrate a dynamic array implementation to solve the problems Note additional data members required –DStack Data MembersDStack Data Members

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Dynamic Array to Store Stack Elements Constructor must –Check that specified numElements > 0 –Set capacity to numElements –Allocate an array pointed to by myArray with capacity = myCapacity –Set myTop to -1 if allocation goes OK Note implementation of constructor for DStackimplementation of constructor Fig 7.6A DStack.h, Fig. 7.6B DStack.cppFig 7.6A DStack.hFig. 7.6B DStack.cpp

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Dynamic Array to Store Stack Elements Class Destructor needed –Avoids memory leak –Deallocates array allocated by constructor Note destructor definitiondestructor definition

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Dynamic Array to Store Stack Elements Copy Constructor needed for –Initializations –Passing value parameter –Returning a function value –Creating a temporary storage value Provides for deep copy Note definitiondefinition

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Dynamic Array to Store Stack Elements Assignment operator –Again, deep copy needed –copies member-by-member, not just address Note implementation of algorithm in operator= definitiondefinition View driver program to test DStack class, Fig Fig. 7.10

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Further Considerations What if dynamic array initially allocated for stack is too small? –Terminate execution? –Replace with larger array! Creating a larger array –Allocate larger array –Use loop to copy elements into new array –Delete old array –Point myArray variable at this new array

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Further Considerations Another weakness – the type must be set with typedef mechanism This means we can only have one type of stack in a program –Would require completely different stack declarations and implementations Solution coming in Chapter 9 –class templates

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Linked Stacks Another alternative to allowing stacks to grow as needed Linked list stack needs only one data member –Pointer myTop –Nodes allocated (but not part of stack class) Note declaration, Fig. 7-11Fig. 7-11

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Implementing Linked Stack Operations Constructor –Simply assign null pointer to myTop Empty –Check for myTop == null Push –Insertion at beginning of list Top –Return data to which myTop points View definitions in Fig Fig View definitions in Fig Fig. 7.12

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Implementing Linked Stack Operations Pop –Delete first node in the linked list ptr = myTop; myTop = myTop->next; delete ptr; Output –Traverse the list for (ptr = myTop; ptr != 0; ptr = ptr->next) out data << endl; View definitions in Fig Fig View definitions in Fig Fig. 7.12

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Implementing Linked Stack Operations Destructor –Must traverse list and deallocate nodes –Note need to keep track of ptr->next before calling delete ptr; Copy Constructor –Traverse linked list, copying each into new node –Attach new node to copy View definitions in Fig Fig View definitions in Fig Fig. 7.12

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Implementing Linked Stack Operations Assignment operator –Similar to copy constructor –Must first rule out self assignment –Must destroy list in stack being assigned a new value View completed linked list version of stack class, Fig 7.12Fig 7.12 Note driver program, Fig. 7.12CFig. 7.12C

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Application of Stacks Consider events when a function begins execution Activation record (or stack frame) is created Stores the current environment for that function. Contents:

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Run-time Stack Functions may call other functions –interrupt their own execution Must store the activation records to be recovered –system then reset when first function resumes execution This algorithm must have LIFO behavior Structure used is the run-time stack

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Use of Run-time Stack When a function is called … Copy of activation record pushed onto run- time stack Arguments copied into parameter spaces Control transferred to starting address of body of function

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Use of Run-time Stack When function terminates Run-time stack popped –Removes activation record of terminated function –exposes activation record of previously executing function Activation record used to restore environment of interrupted function Interrupted function resumes execution

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Application of Stacks Consider the arithmetic statement in the assignment statement: x = a * b + c Compiler must generate machine instructions 1.LOAD a 2.MULT b 3.ADD c 4.STORE x Note: this is "infix" notation The operators are between the operands Note: this is "infix" notation The operators are between the operands

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved RPN or Postfix Notation Most compilers convert an expression in infix notation to postfix –the operators are written after the operands So a * b + c becomes a b * c + Advantage: –expressions can be written without parentheses

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Postfix and Prefix Examples INFIX RPN (POSTFIX) PREFIX A + B A * B + C A * (B + C) A - (B - (C - D)) A - B - C - D A B * C + A B C + * A B C D--- A B-C-D- + * A B C * A + B C -A-B-C D ---A B C D A B ++ A B Prefix : Operators come before the operands

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved  *  *  *  Evaluating RPN Expressions "By hand" (Underlining technique): 1. Scan the expression from left to right to find an operator. 2. Locate ("underline") the last two preceding operands and combine them using this operator. 3. Repeat until the end of the expression is reached. Example: *  * 2 8 *  16

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Evaluating RPN Expressions By using a stack algorithm 1.Initialize an empty stack 2.Repeat the following until the end of the expression is encountered a)Get the next token (const, var, operator) in the expression b)Operand – push onto stack Operator – do the following i.Pop 2 values from stack ii.Apply operator to the two values iii.Push resulting value back onto stack 3.When end of expression encountered, value of expression is the (only) number left in stack Note: if only 1 value on stack, this is an invalid RPN expression

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Evaluation of Postfix Note the changing status of the stack

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Converting Infix to RPN By hand: Represent infix expression as an expression tree: A * B + C + C * A B A * (B + C) ((A + B) * C) / (D - E) * A + B C C A B D E * + / -  x y x  y

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved C AB D E * + / - Traverse the tree in Left-Right-Parent order (postorder) to get RPN: C AB D E * + / - Traverse tree in Parent-Left-Right order (preorder) to get prefix: Traverse tree in Left-Parent-Right order (inorder) to get infix: — must insert ()'s AB+C*DE-/ - D E (A + B)( * C) /( )(D - E) C AB D E * + / - / * + A B C

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved By hand: "Fully parenthesize-move-erase" method: 1. Fully parenthesize the expression. 2. Replace each right parenthesis by the corresponding operator. 3. Erase all left parentheses. Examples: A * B + C   ((A B * C +  A B * C + A * (B + C)   (A (B C + *  A B C + * ((A * B) + C) (A * (B + C) ) Another RPN Conversion Method

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stack Algorithm 1.Initialize an empty stack of operators 2.While no error && !end of expression a)Get next input "token" from infix expression b)If token is … i."(" : push onto stack ii.")" : pop and display stack elements until "(" occurs, do not display it const, var, arith operator, left or right paren

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stack Algorithm iii.operator if operator has higher priority than top of stack push token onto stack else pop and display top of stack repeat comparison of token with top of stack iv.operand display it 3.When end of infix reached, pop and display stack items until empty Note: Left parenthesis in stack has lower priority than operators

Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Sample Program Converts infix expression to postfix –Uses Stack data type (dynamically allocated version) –View Fig 7.15Fig 7.15 –User enters elements of infix expressions separated by spaces –Program generates postfix expression –Also notes invalid infix expressions