5.1 The Stack Abstract Data Type

Slides:



Advertisements
Similar presentations
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Advertisements

The unorganized person’s data structure
Stacks Chapter 11.
COMPSCI 105 S Principles of Computer Science 13 Stacks.
EC-211 DATA STRUCTURES LECTURE 5. 2 Stack Data Structure Stack of Books Stack of Notes Stack of Gifts.
Stacks Chapter 5. Chapter Objectives  To learn about the stack data type and how to use its four methods: push, pop, peek, and empty  To understand.
Chapter 3 Stacks.
CHAPTER 3 Stacks. Chapter Objectives  To learn about the stack data type and how to use its four methods:  push  pop  peek  empty  To understand.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Stacks (Revised and expanded from CIT 591). What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on.
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
30-Jun-15 Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Stacks.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Chapter 3 Stacks.
CHAPTER 3 Stacks MIDTERM OCTOBER 17 IN LAB. Chapter Objectives  To learn about the stack data type and how to use its four methods:  push  pop  peek.
Ceng-112 Data Structures ITurgut Kalfaoglu 1 Chapter 3 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.
Data Structures: CSCI 362 – Stack Implementation Data Structures: CSCI 362 – Stack Implementation lecture notes adapted from Data Structures with C++ using.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
1 Stacks Stack Examples Stack API More Examples/Uses Base Conversion Activation Records RPN Implementing a Stack Stacks.
Chapter 7 Stacks I CS Data Structures I COSC 2006 April 22, 2017
Computer Science Department Data Structure & Algorithms Problem Solving with Stack.
COMP 121 Week 13: Stacks. Objectives Learn about the stack data type and how to use its four methods: push, pop, peek, and empty Understand how Java implements.
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)
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.
Lecture objectives  Collections interface  Learn about stacks and their methods:  push  pop  peek  Empty  Analyze stack applications and why stacks.
Data Structures & Algorithms
Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
Fall 2006 METU EEEEE 441 S. Ece (GURAN) SCH MIDT EE 441 Data Structures Lecture 6 Stacks and Queues.
Chapter 4 ADTs Stack and Queue. 4-2 Formal ADT Specifications The Java interface construct lets us collect together method interfaces into a syntactic.
Main Index Contents 11 Main Index Contents Stacks Further Stack Examples Further Stack Examples Pushing/Popping a Stack Pushing/Popping a Stack Class StackClass.
Click to edit Master text styles Stacks Data Structure.
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(),
1 Data Structures CSCI 132, Spring 2016 Notes_ 5 Stacks.
ADT Stack & Queue - Case Studies TCP1201: 2013/2014.
Sorts, CompareTo Method and Strings
Chapter 4 Stacks
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
Stacks Chapter 5.
MIDTERM OCTOBER 17 IN LAB Chapter 3 Stacks.
Stacks Stacks.
Revised based on textbook author’s notes.
Stacks Chapter 7 introduces the stack data type.
Stacks Chapter 4.
Algorithms and Data Structures
Stack.
Chapter 5 Stacks.
Tuesday, February 20, 2018 Announcements… For Today… 4+ For Next Time…
5.4 Additional Stack Applications
MIDTERM OCTOBER 11 IN LAB Chapter 3 Stacks.
Stacks.
Stacks.
Chapter 4: Control Structures I (Selection)
Stacks.
Topic 15 Implementing and Using Stacks
Jordi Cortadella and Jordi Petit Department of Computer Science
Stack.
Stacks.
5.3 Implementing a Stack Chapter 5 – The Stack.
5.1 The Stack Abstract Data Type
Presentation transcript:

5.1 The Stack Abstract Data Type 5.2 Stack Applications Chapter 5 – The Stack

Attendance Quiz #18 Stacks

Tip #19: Initialization Lists Stacks Initialization rules are fickle: int x[10]; vector<int> x; The best way to deal with this this seemingly indeterminate state of affairs is to always initialize your objects before you use them! The responsibility for initialization falls on the constructors. The rule: make sure that all constructors initialize everything in the object! But, don't confuse assignment with initialization! Initialization is creating an instance (of type) with certain value. Assignment is to give value to an already created instance (of type). Construct name with an object value representing an empty string. Then assign to this already initialized variable the value s. Construct name with an object value of variable s (constructors will be called once.) class Person { private: string name; public: Person(string s) { this->name = s; } }; class Person { private: string name; public: Person(string s) : name(s) { } };

5.1, pgs. 312-315 5.1 The Stack Abstract Data Type Specification of the Stack Abstract Data Type 5.1, pgs. 312-315

The Stack Objectives: Stacks are Specialized Lists To learn about the stack data type and how to use its four functions: push, pop, top, and empty To understand how C++ 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 Stacks are Specialized Lists A client using a list can access any element, remove any element, and insert an element anywhere in the list. A client using a stack can access (and remove) only the most recently inserted element, and can insert an element only at the “top” of the stack. Stacks are among the most commonly used data structures in computer science.

Stack Abstract Data Type Stacks A stack can be compared to a Pez dispenser Only the top item can be accessed You can extract only one item at a time The top element in the stack is the last added to the stack (most recently). The stack’s storage policy is Last-In, First-Out, or LIFO. Only the top element of a stack is visible; therefore the number of operations performed by a stack are few:

A Stack of Strings stack<string> names; names.push("Rich"); names.push("Debbie"); names.push("Robin"); names.push("Dustin"); names.push("Jonathan"); cout << names.empty(); string last = names.top(); names.pop(); names.push("Philip");

myStack.h Let's use a vector for our stack. Stacks #ifndef MY_STACK_H_ #define MY_STACK_H_ #include <vector> template <typename T> class Stack { private: std::vector<T> myStack; public: /** Construct an empty stack */ Stack() {} /** Push item on stack */ void push(const T& item) { myStack.push_back(item); } /** Return top of stack */ T& top() { return myStack.back(); } /** Pop top of stack */ void pop() { myStack.pop_back(); } /** Return TRUE if stack is empty */ bool empty() const { return myStack.size() == 0; } /** Return number of stack entries */ size_t size() const { myStack.size(); } }; #endif // MY_STACK_H_ Let's use a vector for our stack. Delegate most functions to the vector stack.

5.2 Stack Applications 5.2, pgs. 315-325 Case Study: Finding Palindromes Case Study: Testing Expressions for Balanced Parentheses 5.2, pgs. 315-325

Finding Palindromes h a n Stacks Palindrome: a string that reads identically in either direction, letter by letter (ignoring case and spaces) kayak Bombard a drab mob Solution: If we scan the input string from left to right and push each character in the input string onto a stack of characters, we can form the reverse of the string by popping the characters and joining them together in the order that they come off the stack For example: The stack at left contains the characters in the string “hanah" If we pop them off and join them together, we get “h" + "a" + “n" + “a" + “h", or the string “hanah" When the stack is empty, we can compare the string we formed with the original If they are the same, the original string is a palindrome. h a n

Balanced Expressions Stacks When analyzing arithmetic expressions, it is important to determine if an expression is balanced with respect to parentheses. The expression below is balanced: (w * (x + y) / z – (p / (r - q))) The problem is complicated if braces or brackets are used in conjunction with parentheses. The expression below is not balanced: (w * [x + y) / z – [p / {r – q}])

Analysis Stacks An expression is balanced if each subexpression that starts with the symbol “{“ ends with the symbol “}”, and the same statement is true for the other symbol pairs. Another way of saying this is that an opening parenthesis at position k in the sequence “{[(“ must be paired with the closing parenthesis at position k in the sequence “}])”. We can use a stack to determine whether the parentheses are balanced (or nested properly): We will scan the expression from left to right, ignoring all characters except for parentheses We will push each open parenthesis onto a stack of characters When we reach a closing parenthesis, we will see whether it matches the open parenthesis symbol on the top of the stack If so, we will pop it off and continue the scan If the characters don’t match or the stack is empty, there is an error in the expression If there are any characters left on the stack when we are finished, that also indicates an error

Design Algorithm for Function is_balanced Stacks Algorithm for Function is_balanced 1. Create an empty stack of characters. 2. Assume that the expression is balanced (balanced is true). 3. Set index to 0. 4. while balanced is true and index < the expression’s length 5. Get the next character in the data string. 6. if the next character is an opening parenthesis 7. Push it onto the stack. 8. else if the next character is a closing parenthesis 9. Pop the top of the stack. 10. if stack was empty or top does not match the closing parenthesis 11. Set balanced to false. 12. Increment index. 13. Return true if balanced is true and the stack is empty.

Balanced Parentheses Example Stacks Expression: (w * [x + y] / z) 1 4 5 6 7 8 9 10 3 2 ( w x + y ] / z ) [ * ( ( balanced : true index : 0

Balanced Parentheses Example Stacks Expression: (w * [x + y] / z) 1 4 5 6 7 8 9 10 3 2 ( w x + y ] / z ) [ * ( [ ( balanced : true index : 0

Balanced Parentheses Example Stacks Expression: (w * [x + y] / z) 1 4 5 6 7 8 9 10 3 2 ( w x + y ] / z ) [ * ( ] [ [ ( Matches! Balanced still true balanced : true index : 0

Balanced Parentheses Example Stacks Expression: (w * [x + y] / z) 1 4 5 6 7 8 9 10 3 2 ( w x + y ] / z ) [ * ( ) ( ( Matches! Balanced still true balanced : true index : 0

Implementation Stacks /** Program to check an expression for balanced parentheses. */ #include <iostream> #include <string> #include "myStack" using namespace std; const string OPEN = "([{"; // set of opening parentheses const string CLOSE = ")]}"; // corresponding closing parentheses. /** Function to determine if open parentheses */ bool is_open(char ch) { return OPEN.find(ch) != string::npos; } /** Function to determine if closing parentheses */ bool is_close(char ch) return CLOSE.find(ch) != string::npos;

Implementation Stacks bool is_balanced(const string& expression) { Stack<char> s; bool balanced = true; string::const_iterator iter = expression.begin(); while (balanced && (iter != expression.end())) char next_ch = *iter; if (is_open(next_ch)) s.push(next_ch); else if (is_close(next_ch)) if (s.empty()) balanced = false; char top_ch = s.top(); s.pop(); balanced = OPEN.find(top_ch) == CLOSE.find(next_ch); } ++iter; return balanced && s.empty();

Implementation /** Main function to test is_balanced. */ int main() { Stacks /** Main function to test is_balanced. */ int main() { cout << "Enter an expression" << endl; string expression; while (getline(cin, expression) && (expression != "")) cout << endl << expression; if (is_balanced(expression)) cout << " is balanced" << endl; } else cout << " is not balanced" << endl; cout << "Enter another expression: "; return 0;

Testing Stacks Provide a variety of input expressions displaying the result true or false. Try several levels of nested parentheses Try nested parentheses where corresponding parentheses are not of the same type Try unbalanced parentheses Try no parentheses at all! PITFALL: If you attempt to pop an empty stack your program will probably halt and report a run-time error. The nature of the error message will depend on the compiler and operating system. It is possible that no error is reported at all. You can guard against this error by testing for a nonempty stack before calling top or pop.

[ ( 3 + 4 ) * [ { 3 - 2 } - ( 2 / 2 ) ] + 24 ] / 3 3 % { 7 - ( 2 / [ ( 5 – 81 ) ] } + 1 )

The Stack

Finding Palindromes Stacks Palindrome: a string that reads identically in either direction, letter by letter (ignoring case) kayak "I saw I was I" “Able was I ere I saw Elba” "Level madam level" Problem: Write a program that reads a string and determines whether it is a palindrome. Analysis: Possible solutions: Set up a loop in which we compare the characters at each end of a string as we work towards the middle - If any pair of characters is different, the string can’t be a palindrome. Scan a string backward (from right to left) and append each character to the end of a new string, which would become the reverse of the original string. Then we can determine see if the strings were equal. (We can use a stack to form the reverse of a string.)

Finding Palindromes w a s I Stacks If we scan the input string from left to right and push each character in the input string onto a stack of characters, we can form the reverse of the string by popping the characters and joining them together in the order that they come off the stack For example, the stack at left contains the characters in the string "I saw" If we pop them off and join them together, we get "w" + "a" + "s" + " " + "I", or the string "was I" When the stack is empty, we can compare the string we formed with the original If they are the same, the original string is a palindrome. w a s I

Design Stacks

myStack.h Let's use a vector for our stack. Stacks #ifndef MY_STACK_H_ #define MY_STACK_H_ #include <vector> template <typename T> class Stack { private: std::vector<T> myStack; public: /** Construct an empty stack */ Stack() {} /** Push item on stack */ void push(const T& item) { myStack.push_back(item); } /** Return top of stack */ T& top() { return myStack.back(); } /** Pop top of stack */ void pop() { myStack.pop_back(); } /** Return TRUE if stack is empty */ bool empty() const { return myStack.size() == 0; } /** Return number of stack entries */ size_t size() const { myStack.size(); } }; #endif // MY_STACK_H_ Let's use a vector for our stack. Delegate most functions to the vector stack.

Palindrome Functor Push lower casepalindrome characters onto stack. Stacks #include <string> #include "myStack.h" using std::string; class Palindrome { private: string palindrome; public: Palindrome(const std::string& str) : palindrome(str) {} bool operator()() Stack<char> myStack; string reverse; for (int i = 0; i < palindrome.size(); ++i) palindrome[i] = tolower(palindrome[i]); myStack.push(palindrome[i]); } while (!myStack.empty()) reverse += myStack.top(); myStack.pop(); return reverse == palindrome; }; #include <iostream> #include "palindrome.h" using namespace std; int main() { string palindrome = "kayaka"; Palindrome Palindrome(palindrome); cout << "\"" << palindrome << "\" is "; if (!Palindrome()) cout << "not "; cout << "a palindrome"; return 0; } Push lower casepalindrome characters onto stack. Pop characters off stack and append in reverse order. Compare strings.

Testing Stacks Test the Palindrome_Finder class using the following inputs (equivalent classes): A single character (always a palindrome) Multiple characters in one word Multiple words Different cases Even-length strings Odd-length strings An empty string (considered a palindrome) Other Questions Null string? Phrase palindromes? Punctuation?