1 / 60

Lecture 6: Stacks

Lecture 6: Stacks. The Abstract Data Type. Specifications of an abstract data type for a particular problem Can emerge during the design of the problem’s solution Examples readAndCorrect algorithm displayBackward algorithm. Developing an ADT During the Design of a Solution.

sereno
Download Presentation

Lecture 6: Stacks

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. Lecture 6: Stacks

  2. The Abstract Data Type • Specifications of an abstract data type for a particular problem • Can emerge during the design of the problem’s solution • Examples • readAndCorrect algorithm • displayBackward algorithm

  3. Developing an ADT During the Design of a Solution • ADT stack operations • Create an empty stack • Destroy a stack • Determine whether a stack is empty • Add a new item to the stack • Remove the item that was added most recently • Retrieve the item that was added most recently

  4. Developing an ADT During the Design of a Solution • A stack • Last-in, first-out (LIFO) property • The last item placed on the stack will be the first item removed • Analogy • A stack of dishes in a cafeteria Figure 6-1 Stack of cafeteria dishes

  5. Refining the Definition of the ADT Stack • Operation Contract for the ADT Stack isEmpty():boolean {query} push(in newItem:StackItemType) throw StackException pop() throw StackException pop(out stackTop:StackItemType) throw StackException getTop(out stackTop:StackItemType) {query} throw StackException

  6. Implementations of the ADT Stack • The ADT stack can be implemented using • An array • A linked list • The ADT list • All three implementations use a StackException class to handle possible exceptions

  7. An Array-Based Implementation of the ADT Stack • Private data fields • An array of items of type StackItemType • The index top to the top item • Compiler-generated destructor and copy constructor Figure 6-5 An array-based implementation

  8. const int MAX_STACK = 20; • typedef int StackItemType; • class Stack • { • public: • Stack(); // default constructor • bool isEmpty() const; • void push(StackItemType newItem) ; • void pop() ; • void pop(StackItemType& stackTop); • void getTop(StackItemType& stackTop) const; • private: • StackItemType items[MAX_STACK]; // array of stack items • int top; // index to top of stack • }; // end class

  9. Stack::Stack(): top(-1) • { • }; // end default constructor • bool Stack::isEmpty() const • { • return top < 0; • }; // end isEmpty

  10. void Stack::push(StackItemType newItem) throw(StackException) • {// if stack has no more room for another item • if (top >= MAX_STACK-1) • throw StackException("StackException: stack full on push"); • else • { ++top; • items[top] = newItem; • } // end if • }; // end push • void Stack::pop() throw(StackException) • { • if (isEmpty()) • throw StackException("StackException: stack empty on pop"); • else • --top; // stack is not empty; pop top • }; // end pop

  11. void Stack::pop(StackItemType& stackTop) throw(StackException) • { • if (isEmpty()) • throw StackException("StackException: stack empty on pop"); • else • { // stack is not empty; retrieve top • stackTop = items[top]; • --top; // pop top • } // end if • }; // end pop • void Stack::getTop(StackItemType& stackTop) const throw(StackException) • { • if (isEmpty()) • throw StackException("StackException: stack empty on getTop"); • else • // stack is not empty; retrieve top • stackTop = items[top]; • }; // end getTop

  12. int main() • { • StackItemType anItem; • Stack aStack; • for (int i = 0; i< 10; i++) • {anItem = i*10; • aStack.push(anItem); // push it onto stack • } • while (!aStack.isEmpty()) • { aStack.getTop(anItem); • cout <<anItem<<endl; • aStack.pop(); • } • return 0; • }//ex6-1.cpp

  13. Implementations of the ADT Stack Figure 6-4 Implementations of the ADT stack that use (a) an array; (b) a linked list; (c) an ADT list

  14. A Pointer-Based Implementation of the ADT Stack • A pointer-based implementation • Enables the stack to grow and shrink dynamically • topPtr is a pointer to the head of a linked list of items • A copy constructor and destructor must be supplied Figure 6-6A pointer-based implementation

  15. Pointer-based Stack • class Stack • {public: • //… • Stack(const Stack& aStack); • //… • ~Stack(); //Destructor; • private: • struct StackNode // a node on the stack • { StackItemType item; // a data item on the stack • StackNode *next; // pointer to next node • }; // end struct • StackNode *topPtr; // pointer to first node in the stack • }; // end class

  16. Stack::Stack() : topPtr(NULL) • {} // end default constructor • Stack::Stack(const Stack& aStack) • { if (aStack.topPtr == NULL) • topPtr = NULL; // original list is empty • else • { // copy first node • topPtr = new StackNode; • topPtr->item = aStack.topPtr->item; • // copy rest of list • StackNode *newPtr = topPtr; // new list pointer • for (StackNode *origPtr = aStack.topPtr->next; origPtr != NULL; • origPtr = origPtr->next) • { newPtr->next = new StackNode; • newPtr = newPtr->next; • newPtr->item = origPtr->item; • } // end for • newPtr->next = NULL; • } // end if • } // end copy constructor

  17. Stack::~Stack() • {while (!isEmpty()) pop(); } // Assertion: topPtr == NULL • bool Stack::isEmpty() const • { return topPtr == NULL; } // end isEmpty • void Stack::push(StackItemType newItem) • { // create a new node • StackNode *newPtr = new StackNode; • // set data portion of new node • newPtr->item = newItem; • // insert the new node • newPtr->next = topPtr; • topPtr = newPtr; • } // end push

  18. void Stack::pop() throw(StackException) • { • if (isEmpty()) • throw StackException("StackException: stack empty on pop"); • else • { // stack is not empty; delete top • StackNode *temp = topPtr; • topPtr = topPtr->next; • // return deleted node to system • temp->next = NULL; // safeguard • delete temp; • } // end if • } // end pop

  19. void Stack::pop(StackItemType& stackTop) throw(StackException) • {if (isEmpty()) throw StackException("StackException: stack empty on pop"); • else • { // stack is not empty; retrieve and delete top • stackTop = topPtr->item; • StackNode *temp = topPtr; • topPtr = topPtr->next; • temp->next = NULL; // safeguard • delete temp; // return deleted node to system • } // end if • } // end pop • void Stack::getTop(StackItemType& stackTop) const throw(StackException) • { if (isEmpty()) throw StackException("StackException: stack empty on getTop"); • else // stack is not empty; retrieve top • stackTop = topPtr->item; • } // end getTop • //ex6-2.cpp

  20. An Implementation That Uses the ADT List • The ADT list can represent the items in a stack • Let the item in position 1 of the list be the top • push(newItem) • insert(1, newItem) • pop() • remove(1) • getTop(stackTop) • retrieve(1, stackTop)

  21. An Implementation That Uses the ADT List Figure 6-7 An implementation that uses the ADT list

  22. Comparing Implementations • Fixed size versus dynamic size • A statically allocated array-based implementation • Fixed-size stack that can get full • Prevents the push operation from adding an item to the stack, if the array is full • A dynamically allocated array-based implementation or a pointer-based implementation • No size restriction on the stack

  23. Comparing Implementations • A pointer-based implementation vs. one that uses a pointer-based implementation of the ADT list • Pointer-based implementation is more efficient • ADT list approach reuses an already implemented class • Much simpler to write • Saves programming time

  24. List Based Stack • Stack • {public: • //… • private: • List aList; // list of stack items • };// others are the same as the Pointer-based

  25. Stack::Stack() • { } // end default constructor • Stack::Stack(const Stack& aStack): aList(aStack.aList) • { } // end copy constructor • Stack::~Stack() • { } // end destructor • bool Stack::isEmpty() const • { • return aList.isEmpty(); • } // end isEmpty

  26. void Stack::push(StackItemType newItem) throw(StackException) • { try { • aList.insert(1, newItem); • } // end try • catch (ListException e) • { throw StackException("StackException: cannot push item"); • } // end catch • } // end push • void Stack::pop() throw(StackException) • { try { • aList.remove(1); • } // end try • catch (ListIndexOutOfRangeException e) • { throw StackException("StackException: stack empty on pop"); • } // end catch • } // end pop

  27. void Stack::pop(StackItemType& stackTop) throw(StackException) • { try { • aList.retrieve(1, stackTop); • aList.remove(1); • } // end try • catch (ListIndexOutOfRangeException e) • { throw StackException("StackException: stack empty on pop"); • } // end catch • } // end pop • void Stack::getTop(StackItemType& stackTop) const throw(StackException) • { try { • aList.retrieve(1, stackTop); • } // end try • catch (ListIndexOutOfRangeException e) • { throw StackException("StackException: stack empty on getTop"); • } // end catch • } // end getTop • //ex6-3.cpp

  28. The STL Class stack • Provides a size function • Has two data type parameters • T, the data type for the stack items • Container, the container class that the STL uses in its implementation of the stack • Uses the keyword explicit in the constructor’s declaration to prevent use of the assignment operator to invoke the constructor

  29. #include <iostream> • #include <stack> • using namespace std; • int main() • { stack<int> aStack; • int item; • // Right now, the stack is empty • if (aStack.empty()) • cout << "The stack is empty." << endl; • for (int j = 0; j < 5; j++) • aStack.push(j); // places items on top of stack • while (!aStack.empty()) • { cout << aStack.top() << endl; • aStack.pop(); • } // end while • return 0; • } // end main • //ex6-4.cpp

  30. Using the ADT Stack in a Solution • A program can use a stack independently of the stack’s implementation • displayBackward algorithm can be refined using stack operations • Use axioms to define an ADT stack formally • Example: Specify that the last item inserted is the first item to be removed (aStack.push(newItem)).pop()= aStack

  31. Checking for Balanced Braces • A stack can be used to verify whether a program contains balanced braces • An example of balanced braces abc{defg{ijk}{l{mn}}op}qr • An example of unbalanced braces abc{def}}{ghij{kl}m

  32. Checking for Balanced Braces • Requirements for balanced braces • Each time you encounter a “}”, it matches an already encountered “{” • When you reach the end of the string, you have matched each “{”

  33. Checking for Balanced Braces Figure 6-3 Traces of the algorithm that checks for balanced braces

  34. 34 bool balanced (string str) • { int index=0; • Stack S; • while (str [index]!= '\0') { • if (str[index] == ‘{' ) • S.push(‘{'); • else if(str[index] == ‘}' ) { • if(!S.isEmpty( )) S.pop( ); • else return 0; • } • ++index; // next character • } • return (S.isEmpty( )); • }//ex6-5.cpp

  35. Recognizing Languages 35 We define a language L as follows: L = {w$w’| w is a character string that does not contain a $ sign. w’ is the reverse of w.} PALINDROMES EXAMPLES: A$A AB$BA ABA$ABA // in language Counter Examples: A$B A$B$B$A A$BA //not in language Basic Idea: Keep pushing characters onto a stack until you see a $. Then keep popping and reading, and compare those characters. Return FALSE if a popped character is different from a read character. Return TRUE if the stack becomes empty and the end of the string is found at the same time.

  36. 36 bool palindrome (string str) • { int index=0; Stack S; • while (str[index] != '$') { • if (str[index] == '\0') return false; • S.push(str[index]); • ++index; } • ++index; char ch; • while (str[index] != '\0') { • if (S.isEmpty( )) return false; • S.getTop(ch); • if (ch != str[index] ) return false; • S.pop( ); • ++index; } • if (S.isEmpty( )) return true; // should be! • else return false; • } //ex6-5.cpp

  37. 37 Evaluating Postfix Expressions: Given is a postfix expression, compute its value. 2 * (3 + 4) (infix) 2 3 4 + * (corresponding postfix) 2 * (3 + 4) -> 14 2 3 4 + * -> 14

  38. 38 Basic Idea: We use a stack again, but this time we put the NUMBERS onto it. Every time we see a number, we push it. Every time we see an operator, we pop off two numbers, apply the operator, and push the result back onto the stack. 2 3 4 + * 2 ... ... Push 2 on the stack 3 ... ... Push 3 on the stack 4 ... ... Push 4 on the stack + ... ... Pop off 4; Pop off 3; add 3 and 4; (ORDER!) Push 7 on stack. * ... ... Pop off 7; Pop off 2; Multiply 2 and 7; Push 14 back on the stack.

  39. 39 Now the same example using the abstract data type. S.Push(2) S.Push(3) S.Push(4) y = S.GetStackTop() S.Pop() x = S.GetStackTop() S.Pop() z = x + y S.Push(z) y = S.GetStackTop() S.Pop() x = S.GetStackTop() S.Pop() z = x * y S.Push(z)

  40. 40 For the program we make a number of simplifying assumptions: • No error checking; No unary operators; Only +,-,*,/ as operators; and Only digit 1-9 as operands • int evaluate (string str) • {Stack S; int x, y, z; • for ( int index =0; index< str.length(); ++index) { // look at each char • if (( str[index]=='+' )||(str[index] == '-')||(str[index] == '*')||(str[index] == '/')) { S.getTop(y); S.pop( ); • S.getTop(x); S.pop( ); • switch (str[index]){case '+': z = x + y; break; case '-': z = x-y; break; • case '*': z = x*y; break; case '/': z = x/y; break; • } ; S.push(z); • } else S.push(str[index]-'0'); • } • S.getTop(z); return z; • }

  41. 41 Converting Infix to Postfix (Complicated) This uses a stack again, but this time it stores the operators and open parentheses, as opposed to the operands. The result is stored in an array “PE”, the postfix expression. Algorithm 1. If an operand appears in the input stream, then append it to the PE array. 2. If a “(“ appears in the input stream, then push it onto the stack. 3. If a “)” appears in the input stream, then pop off elements from the stack and append them to the PE array until an open parenthesis is found on the stack. Pop off and discard the (

  42. 42 4. If an operator appears in the input stream, then: IF the stack is NOT EMPTY then pop off operators of greater or equal precedence from the stack and append them to PE, until: a) either: the stack is empty b) or: you find an “(“ on the stack c) or: you find an operator of lower precedence Then push the new operator on the stack. 5. When you reach the end of the input, then pop off all operators from the stack and append them to the end of PE.

  43. 43 Now we will show an example of how to actually do this. We convert: A - (B + C * D) / E We will show the stack top on the RIGHT. CH= A S= PE= A 1. CH= - S= - PE= A 4.d) CH= ( S= -( PE= A 2. CH= B S= -( PE= AB 1. CH= + S= -(+ PE= AB 4.b) CH= C S= -(+ PE= ABC 1. CH= * S= -(+* PE= ABC 4.c) CH= D S= -(+* PE= ABCD 1. CH= ) S= -(+ PE= ABCD* 3. S= -( PE= ABCD*+ 3. S= - PE= ABCD*+ 3. CH= / S= -/ PE= ABCD*+ 4.d) CH= E S= -/ PE= ABCD*+E 1. S= - PE= ABCD*+E/ 5. S= PE= ABCD*+E/- 5.

  44. 44 Why does this work? This algorithm is based on the following observations: 1) Operands stay in the same order. A+B becomes AB+ and NOT BA+ 2) Operators move only to the right, never to the left, relative to the operands. A+B ---> AB+ + moved to the right of B. 3) Postfix expressions don’t need parenthesis.

  45. string infixToPostfix (string str) • {Stack S; string result; int y; • for ( int index =0; index< str.length(); ++index) { • // look at each char • switch (str[index]) { • case '(': S.push (str[index]); break; • case ')': • if (!S.isEmpty()){ S.pop(y); • while (char (y) !='(') {result+=char(y); S.pop(y); }; • } • break;

  46. case '+': case '-': case '*': case '/': • if (!S.isEmpty()){S.getTop(y); • while ((!S.isEmpty())&& (char(y)!='(') &&(pre(str[index])<= pre(y))) • { result+=char(y);S.pop();S.getTop(y);} } • S.push (str[index]); • break; • default: • if (str[index]<='Z'&&str[index]>='A')||(str[index]<='z'&&str[index]>='a')) • result+=str[index]; • } • }

  47. while (!S.isEmpty()) {S.pop(y); • if ((char(y) == '+')||(char(y) == '-')||(char(y) == '*')||(char(y) == '/'))result+=char(y); • else return "Error!"; • } • return result; • }

  48. 48 Search This section uses a structure called a graph that will be covered in more detail much later in the class. Given is the following problem: There is a map of cities, and there is a flight plan that describes all connections between cities. Then you are given two specific cities, A and B and asked whether you can fly from A to B. Note: In a real flight plan you can’t be sure that there is a flight from B to A. We will use examples that make this assumption. In fact, there will be “dead-end cities” with no flights leaving. (Flights in, No flights out) Of course this problem uses a stack, but we start with the representation of the map.

  49. 49 Example: Y Z W S T Q X R P

  50. 50 How do we represent this “graph” in the computer? There are two possibilities, but for now we will learn only one: The Adjacency List. An adjacency list is really an ARRAY OF LINKED LISTS. For every city there is one element in the array. This element is a pointer to a linked list. Every element of the linked list contains the name of ONE NEIGHBORING CITY.

More Related