ECE 551 C++ Programming, Data structures, and Algorithms Abstract Data Type: Stack Last In First Out (LIFO) 1 2 2 1 4 3 1 3 4 Stacks in Programming Worst line ever! 5 3 1 5 Stacks are not useful for waiting in line, but... Have already seen one important stack Call stack: tracks local variables, parameters, return locations Implicitly part of language, does not need explicit ADT Useful for reversing things Push each thing on the stack in order Popping the stack gives elements in reverse order Don t overcomplicate simple reversals though! Useful for nested matching Example: nested parenthesis ( 4 + (3 * 2) - (8 * 9) + 1) Also, html, xml, etc.. More generally, useful for parsing Analyzing an input string to determine meaning According to a grammar (fixed formal set of rules) 6
Use a Stack, it starts out empty... Start reading the input (just strings) push it on the stack 7 8 push it on the stack push it on the stack 9 10 All the tags on the stack apply to any (non-tag) we encounter Encounter a close tag: pop the stack (remove its top) 11 12
Encounter a close tag: pop the stack (remove its top) <i> <b> 13 14 Stack Example: Undo Many editing tools have Undo feature Also works with a stack Push each change (or document state) onto a stack Undo reverts the last change (LIFO) Redo functionality: put undone changes onto another stack 15 16 17 18
bool isempty() const; //check empty 19 20 bool isempty() const; //check empty int size() const; //how many? }; virtual void push(t item) = 0; virtual T pop() = 0; virtual T & peek() = 0; virtual bool isempty() const = 0; virtual int size() const = 0; }; ADT: so all methods abstract (pure virtual) 21 22 Push: increment TOS, store data there tos = -1 tos = 01-1 A B 23 24
Peek : Examine data[tos] Pop: result is data[tos] decrement tos tos = 1 A B tos = 10 A B 25 26 tos = 09 A BC D E F G H I J K If we push a bunch of elements... tos = 9 Our stack is full Similar options to Queue: Error: rely on users not to push or Grow: resize array A BC D E F G H I J K Growing is easier than Queue: C: realloc the array C++: new array, copy elements (or use a vector) 27 28 Wrap Up: Stacks Stacks: Last In First Out Example uses Parsing/matching balanced items Undo/redo stacks Could use array implementation... Or we could use a Linked List Next segment 29