Presentation is loading. Please wait.

Presentation is loading. Please wait.

6/12/20161 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the.

Similar presentations


Presentation on theme: "6/12/20161 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the."— Presentation transcript:

1 6/12/20161 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the data –Error conditions associated with operations

2 6/12/20162 The Stack ADT The Stack ADT stores arbitrary objects. Insertions and deletions follow the last-in first-out (LIFO) scheme. The last item placed on the stack will be the first item removed. (similar to a stack of dishes) Stack of Dishes

3 6/12/20163 ADT Stack Operations Create an empty stack Destroy a stack Determine whether a stack is empty Add a new item -- push Remove the item that was added most recently -- pop Retrieve the item that was added most recently pushpop Stack top

4 6/12/20164 ADT Stack Operations(cont.) createStack() –creates a an empty stack destroyStack() –destroys a stack isEmpty():boolean –determines whether a stack is empty or not push(in newItem:StackItemType) throw StackException –Adds newItem to the top of a stack pop() throw StackException pop(out stackTop:StackItemType) throw StackException –Removes the top of a stack (ie. removes the item that was added most recently getTop(out stackTop:StackItemType) throw StackException –Retrieves the top of stack into stackTop

5 6/12/20165 A Simple Stack Application -- Undo sequence in a text editor Problem: abcd   fg   abf // Reads an input line. Enter a character or a backspace character (  ) readAndCorrect(out aStack:Stack) aStack.createStack() read newChar while (newChar is not end-of-line symbol) { if (newChar is not backspace character) aStack.push(newChar) else if (!aStack.isEmpty()) aStack.pop() read newChar }

6 6/12/20166 A Simple Stack Application -- Display Backward Display the input line in reversed order by writing the contents of stack aStack. displayBackward(in aStack:Stack) while (!aStack.isEmpty())) { aStack.pop(newChar) write newChar }

7 6/12/20167 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 Requirements for balanced braces –Each time we encounter a “}”, it matches an already encountered “{” –When we reach the end of the string, we have matched each “{”

8 6/12/20168 Checking for Balanced Braces -- Traces

9 6/12/20169 Checking for Balanced Braces -- Algorithm aStack.createStack(); balancedSoFar = true; i=0; while (balancedSoFar and i < length of aString) { ch = character at position i in aString;i++; if (ch is ‘{‘)// push an open brace aStack.push(‘{‘); else if (ch is ‘}’)// close brace if (!aStack.isEmpty()) aStack.pop();// pop a matching open brace else// no matching open brace balancedSoFar = false; // ignore all characters other than braces } if (balancedSoFar and aStack.isEmpty()) aString has balanced braces else aString does not have balanced braces

10 6/12/201610 Recognizing Strings in a Language L = {w$w’ : w is a possible empty string of characters other than $, w’ = reverse(w) } –abc$cba, a$a, $ are in the language L –abc$abc, a$b, a$ are not in the language L Problem: Deciding whether a given string in the language L or not. A solution using a stack –Traverse the first half of the string, pushing each character onto a stack –Once you reach the $, for each character in the second half of the string, match a popped character off the stack

11 6/12/201611 Recognizing Strings in a Language -- Algorithm aStack.createStack(); i=0; ch = character at position i in aString; while (ch is not ‘$’) { // push the characters before $ (w) onto the stack aStack.push(ch); i++; ch = character at position i in aString; } i++; inLanguage = true; // skip $; assume string in language while (inLanguage and i <length of aString) // match the reverse of if (aStack.isEmpty()) inLanguage = false; // first part shorter than second part else { aStack.pop(stackTop); ch = character at position i in aString; if (stackTop equals to ch) i++;// characters match else inLanguage = false;// characters do not match } if (inLanguage and aStack.isEmpty()) aString is in language else aString is not in language

12 6/12/201612 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

13 6/12/201613 Implementations of the ADT Stack (cont.) 2 1 0

14 6/12/201614 An Array-Based Implementation of the ADT Stack Private data fields –An array of items of type StackItemType –The index top Compiler-generated destructor and copy constructor

15 6/12/201615 An Array-Based Implementation –Header File #include "StackException.h" const int MAX_STACK = maximum-size-of-stack; typedef desired-type-of-stack-item StackItemType; class Stack { public: Stack(); // default constructor; copy constructor and destructor are supplied by the compiler // stack operations: bool isEmpty() const; // Determines whether a stack is empty. void push(StackItemType newItem) throw(StackException); // Adds an item to the top of a stack. void pop() throw(StackException);// Removes the top of a stack. void topAndPop(StackItemType& stackTop) throw(StackException); void getTop(StackItemType& stackTop) const throw(StackException); // Retrieves top of stack. private: StackItemType items[MAX_STACK]; // array of stack items int top; // index to top of stack };

16 6/12/201616 An Array-Based Implementation isEmpty - push #include "StackA.h" // Stack class specification file Stack::Stack(): top(-1) {} // default constructor bool Stack::isEmpty() const { return top < 0; } 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; }}

17 6/12/201617 An Array-Based Implementation – pop void Stack::pop() throw(StackException) { if (isEmpty()) throw StackException("StackException: stack empty on pop"); else --top; // stack is not empty; pop top } void Stack::topAndPop(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 }}

18 6/12/201618 An Array-Based Implementation – getTop 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]; }

19 6/12/201619 An Array-Based Implementation – main #include #include "StackA.h" int main() { StackItemType anItem; Stack aStack; cin >> anItem; // read an item aStack.push(anItem); // push it onto stack return 0; }

20 6/12/201620 A Pointer-Based Implementation of the ADT Stack A pointer-based implementation –Required when the stack needs to grow and shrink dynamically top is a reference to the head of a linked list of items A copy constructor and destructor must be supplied

21 6/12/201621 A Pointer-Based Implementation – Header File #include "StackException.h" typedef desired-type-of-stack-item StackItemType; class Stack{ public: Stack(); // default constructor Stack(const Stack& aStack); // copy constructor ~Stack(); // destructor bool isEmpty() const; void push(StackItemType newItem); void pop() throw(StackException); void topAndPop(StackItemType& stackTop) throw(StackException); void getTop(StackItemType& stackTop) const throw(StackException);

22 6/12/201622 A Pointer-Based Implementation – Header File private: struct StackNode { // a node on the stack StackItemType item; // a data item on the stack StackNode *next; // pointer to next node }; StackNode *topPtr; // pointer to first node in the stack };

23 6/12/201623 A Pointer-Based Implementation – constructor #include "StackP.h" // header file #include // for NULL #include // for assert Stack::Stack() : topPtr(NULL) {} // default constructor Stack::Stack(const Stack& aStack) {// copy constructor 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; } newPtr->next = NULL; }}

24 6/12/201624 A Pointer-Based Implementation – destructor - isEmpty Stack::~Stack() { // pop until stack is empty while (!isEmpty()) pop(); // Assertion: topPtr == NULL } bool Stack::isEmpty() const { return topPtr == NULL; }

25 6/12/201625 A Pointer-Based Implementation – push 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; }

26 6/12/201626 A Pointer-Based Implementation – pop 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; }

27 6/12/201627 A Pointer-Based Implementation – pop void Stack::topAndPop(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; // return deleted node to system temp->next = NULL; // safeguard delete temp; }

28 6/12/201628 A Pointer-Based Implementation – getTop 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; }

29 6/12/201629 An Implementation That Uses the ADT List The ADT list can be used to represent the items in a stack If the item in position 1 is the top –push(newItem) insert(newItem,zeroth()) –pop() remove(first().retrieve()) –getTop(stackTop) first().retrieve()

30 6/12/201630 Comparing Implementations Fixed size versus dynamic size –An array-based implementation Prevents the push operation from adding an item to the stack if the stack’s size limit has been reached A pointer-based implementation –Does not put a limit on the size of the stack An implementation that uses a linked list versus one that uses a pointer-based implementation of the ADT list –Linked list approach is more efficient –ADT list approach reuses an already implemented class Much simpler to write Saves time

31 6/12/201631 Application: Algebraic Expressions When the ADT stack is used to solve a problem, the use of the ADT’s operations should not depend on its implementation To evaluate an infix expression –Convert the infix expression to postfix form –Evaluate the postfix expression Infix ExpressionPostfix Expression 5 + 2 * 35 2 3 * + 5 * 2 + 35 2 * 3 + 5 * ( 2 + 3 ) - 45 2 3 + * 4 -

32 6/12/201632 Evaluating Postfix Expressions When an operand is entered, the calculator –Pushes it onto a stack When an operator is entered, the calculator –Applies it to the top two operands of the stack –Pops the operands from the stack –Pushes the result of the operation on the stack

33 6/12/201633 Evaluating Postfix Expressions – 2 3 4 + *

34 6/12/201634 Converting Infix Expressions to Postfix Expressions An infix expression can be evaluated by first being converted into an equivalent postfix expression Facts about converting from infix to postfix –Operands always stay in the same order with respect to one another –An operator will move only “to the right” with respect to the operands –All parentheses are removed

35 6/12/201635 Converting Infix Expr. to Postfix Expr. -- Algorithm for (each character ch in the infix expression) { switch (ch) { case operand: // append operand to end of postfixExpr postfixExpr=postfixExpr+ch; break; case ‘(‘:// save ‘(‘ on stack aStack.push(ch); break; case ‘)’:// pop stack until matching ‘(‘, and remove ‘(‘ while (top of stack is not ‘(‘) { postfixExpr=postfixExpr+(top of stack); aStack.pop(); } aStack.pop(); break;

36 6/12/201636 Converting Infix Expr. to Postfix Expr. -- Algorithm case operator:// process stack operators of greater precedence while (!aStack.isEmpty() and top of stack is not ‘(‘ and precedence(ch) <= precedence(top of stack) ) { postfixExpr=postfixExpr+(top of stack); aStack(pop); } aStack.push(); break;// save new operator } } // end of switch and for // append the operators in the stack to postfixExpr while (!isStack.isEmpty()) { postfixExpr=postfixExpr+(top of stack); aStack(pop); }

37 6/12/201637 Converting Infix Expressions to Postfix Expressions a - (b + c * d)/ e  a b c d * + e / -

38 6/12/201638 Application: A Search Problem Problem: For each customer request, indicate whether a sequence of flights exists from the origin city to the destination city The flight map is a directed graph –Adjacent vertices are two vertices that are joined by an edge –A directed path is a sequence of directed edges A Flight Map

39 6/12/201639 A Nonrecursive Solution That Uses a Stack The solution performs an exhaustive search –Beginning at the origin city, the solution will try every possible sequence of flights until either It finds a sequence that gets to the destination city It determines that no such sequence exists Backtracking can be used to recover from a wrong choice of a city

40 6/12/201640 A Nonrecursive Solution -- Algorithm searchS(in originCity:City, in destinationCity:City) : boolean // searches for a sequence of flights from originCity to destinationCity aStack.createStack(); clear marks on all cities; aStack.push(originCity); mark origin as visited; while (!aStack.isEmpty() and destinationCity is not at top of stack) { if (no flights exist from city on top of stack to unvisited cities) aStack.pop();// backtrack else { select an unvisited destination city C for a flight from city on top of stack; aStack.push(C); mark C as visited; }} if (aStack.isEmpty()) return false;// no path exists else return true;// path exists

41 6/12/201641 A Nonrecursive Solution -- Trace P is origin city; Z is destination city

42 6/12/201642 A Recursive Solution for Search Problem searchR(in originCity:City, in destinationCity:City):boolean mark originCity as visited; if (originCity is destinationCity) Terminate -- the destination is reached else for (each unvisited city C adjacent to originCity) searchR(C, destinationCity);

43 6/12/201643 The Relationship Between Stacks and Recursion A strong relationship exists between recursion and stacks Typically, stacks are used by compilers to implement recursive methods –During execution, each recursive call generates an activation record that is pushed onto a stack Stacks can be used to implement a nonrecursive version of a recursive algorithm

44 6/12/201644 C++ Run-time Stack The C++ run-time system keeps track of the chain of active functions with a stack When a function is called, the run-time system pushes on the stack a frame containing –Local variables and return value When a function returns, its frame is popped from the stack and control is passed to the method on top of the stack main() { int i = 5; foo(i); } foo(int j) { int k; k = j+1; bar(k); } bar(int m) { … } main i = 5 foo j = 5 k = 6 bar m = 6 Run-time Stack

45 6/12/201645 Example: Factorial function int fact(int n) { if (n ==0) return (1); else return (n * fact(n-1)); }

46 6/12/201646 Tracing the call fact (3) N = 3 if (N==0) false return (3*fact(2)) After original call N = 2 if (N==0) false return (2*fact(1)) N = 3 if (N==0) false return (3*fact(2)) After 1 st call N = 1 if (N==0) false return (1*fact(0)) N = 2 if (N==0) false return (2*fact(1)) N = 3 if (N==0) false return (3*fact(2)) After 2 nd call N = 0 if (N==0) true return (1) N = 1 if (N==0) false return (1*fact(0)) N = 2 if (N==0) false return (2*fact(1)) N = 3 if (N==0) false return (3*fact(2)) After 3rd call

47 6/12/201647 Tracing the call fact (3) N = 3 if (N==0) false return (3* 2) After return from 1st call N = 2 if (N==0) false return (2* 1) N = 3 if (N==0) false return (3*fact(2)) After return from 2nd call N = 1 if (N==0) false return (1* 1) N = 2 if (N==0) false return (2*fact(1)) N = 3 if (N==0) false return (3*fact(2)) After return from 3rd call return 6

48 6/12/201648 Stacks -- Summary ADT stack operations have a last-in, first-out (LIFO) behavior There are different stack implementations –Two Major Implementations: Array-Based, Pointer-Based Many stack applications –expression processing –language recognition –search problem A strong relationship exists between recursion and stacks –Any recursive program can be rewritten as a nonrecursive program using stacks.


Download ppt "6/12/20161 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: –Data stored –Operations on the."

Similar presentations


Ads by Google