1 / 96

Data Structure

Data Structure. Dr. Mohamed Khafagy. Stacks. Stack: what is it? ADT Applications Implementation(s). What is a stack?. Stores a set of elements in a particular order Stack principle: LAST IN FIRST OUT = LIFO

urbain
Download Presentation

Data Structure

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. Data Structure Dr. Mohamed Khafagy

  2. Stacks • Stack: what is it? • ADT • Applications • Implementation(s)

  3. What is a stack? • Stores a set of elements in a particular order • Stack principle: LAST IN FIRST OUT • = LIFO • It means: the last element inserted is the first one to be removed • Example • Which is the first element to pick up? • A stack is an ordered list in which insertions and deletions are made at one end called the top. It is also called a Last-In-First-Out (LIFO) list.

  4. Stacks (2) • A PEZ ® dispenser as an analogy:

  5. top F top E E D D C C B B bottom bottom A A Stack Of Cups • Add a cup to the stack. • Remove a cup from new stack. • A stack is a LIFO list.

  6. Last In First Out top B A C B A D C B A E D C B A D C B A top top top top A

  7. Stack (Cont.) • Given a stack S =(a0, …, an-1),a0 is the bottom element, an-1 is the top element, and ai is on top of element ai-1, 0 < i < n. a3 a3 a2 a2 a1 a1 a0 a0 Push (Add) Pop (Delete)

  8. Exercise: Stacks • Describe the output of the following series of stack operations • Push(8) • Push(3) • Pop() • Push(2) • Push(5) • Pop() • Pop() • Push(9) • Push(1)

  9. Stack Applications • Real life • Pile of books • Plate trays • More applications related to computer science • Program execution stack (read more from your text) • Evaluating expressions

  10. More applications related to computer science • Page-visited history in a Web browser • Undo sequence in a text editor • Saving local variables when one function calls another, and this one calls another, and so on.

  11. objects: a finite ordered list with zero or more elements.methods: for all stack Stack, item  element, max_stack_size  positive integerStack createS(max_stack_size) ::= create an empty stack whose maximum size is max_stack_size BooleanisFull(stack, max_stack_size) ::= if (number of elements in stack == max_stack_size) return TRUEelse return FALSEStack push(stack, item) ::=if (IsFull(stack)) stack_fullelse insert item into top of stack and return Stack ADT

  12. Boolean isEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUEelse return FALSEElement pop(stack) ::= if(IsEmpty(stack)) returnelse remove and return the item on the top of the stack. Stack ADT (cont’d)

  13. Array-based Stack Implementation • Allocate an array of some size (pre-defined) • Maximum N elements in stack • Bottom stack element stored at element 0 • last index in the array is the top • Increment top when one element is pushed, decrement after pop

  14. Implementation of Stack by Array an-1 a2 a1 a0 an-1 a0 a1 a2 Array index 0 1 2 3 n-1

  15. StackcreateS(max_stack_size) ::= #define MAX_STACK_SIZE 100 /* maximum stack size */typedefstruct {int key; /* other fields */ } element; element stack[MAX_STACK_SIZE];int top = -1;BooleanisEmpty(Stack) ::= top< 0;BooleanisFull(Stack) ::= top >= MAX_STACK_SIZE-1; Stack Implementation: CreateS, isEmpty, isFull

  16. The Class Stack template<class T> class Stack { public: Stack(intstackCapacity = 10); ~Stack() {delete [] stack;} boolIsEmpty() const; T& Top() const; void Push(const T& item); void Pop(); private: T *stack; // array for stack elements int top; // position of top element int capacity; // capacity of stack array };

  17. Constructor template<class T> Stack<T>::Stack(intstackCapacity) :capacity(stackCapacity) { if (capacity < 1) throw “Stack capacity must be > 0”; stack = new T[capacity]; top = -1; }

  18. IsEmpty template<class T> inline bool Stack<T>::IsEmpty() const {return top == -1}

  19. Top template<class T> inline T& Stack<T>::Top() const { if (IsEmpty()) throw “Stack is empty”; return stack[top]; }

  20. top a b c d e 0 1 2 3 4 Push template<class T> void Stack<T>::Push(const T& x) {// Add x to the stack. if (top == capacity - 1) {ChangeSize1D(stack, capacity, 2*capacity); capacity *= 2; } // add at stack top stack[++top] = x; }

  21. top a b c d e 0 1 2 3 4 Pop void Stack<T>::Pop() { if (IsEmpty()) throw “Stack is empty. Cannot delete.”; stack[top--].~T(); // destructor for T }

  22. void push(pnode top, element item){ /* add an element to the top of the stack */ pnode temp = (pnode) malloc (sizeof (node)); if (IS_FULL(temp)) { fprintf(stderr, “ The memory is full\n”); exit(1); } temp->item = item; temp->next= top; top= temp; } List-based Stack Implementation: Push

  23. element pop(pnode top) {/* delete an element from the stack */ pnode temp = top; element item; if (IS_EMPTY(temp)) { fprintf(stderr, “The stack is empty\n”); exit(1); } item = temp->item; top = temp->next; free(temp); return item;} Pop

  24. Application of Stack ADT Infix Expressions - An expression in which every binary operation appears between its operands Example: (i) a+b – “+” is a binary operation and a and b are its operands (ii) (a+b)*c

  25. Prefix Expressions An expression in which operator comes before its operands Example: (i) a+b  +ab (ii) (a+b)*c  *+abc (iii) a+(b*c)  +a*bc Postfix Expressions An expression in which operator comes after its operands Example: (i) a+b  ab+ (ii) (a+b)*c  ab+c* (iii) a+(b*c) abc*+

  26. Infix expressions: • Every binary operator appears between its operands. • a + b • a + b * c, if you want to compute a + b first, then (a + b) * c • Prefix expressions: • Every binary operator appears before its operands. No parentheses needed • a + b => + a b • (a + b) * c => * + a b c • Postfix expressions • Every binary operator appears after its operands. No parentheses need • a + b => a b + • (a + b) * c => a b + c * Easy to evaluate using a stack

  27. Postfix notation • Widely used in real compilers for programming languages. • The programmer’s expression is first converted to an equivalent postfix expression. • We can then very easily generate code for evaluating the postfix expression. • Evaluation of postfix expressions have a very direct correspondence with manipulation of stacks.

  28. Postfix evaluation - Example • Expression Code Stack Contents • <> • 3 5 + 8 6 - *push 3 <3> • ^ push 5 <3,5> • add <8> • 3 5 + 8 6 - * push 8 <8,8> • ^ push 6 <8,8,6> • sub <8, 2> • 3 5 + 8 6 - * mul <16> • ^

  29. Assumptions: syntactically correct, no unary operations, and single digit operands 2 3 4 + * for ( (c = cin.get( )) != ‘\n’) { if ( c >= ‘0’ && c <= ‘9’ ) aStack.push(atoi(c)); else { aStack.pop(op2); aStack.pop(op1); switch (c) { case ‘+’: aStack.push(op1 + op2); break; case ‘-’; aStack.push(op1 – op2); break; ….; default: cerr << “panic!”; break; } } } Operations Stack push 2: 2 push 3: 2 3 push 4: 2 3 4 pop 2 3 pop 2 Sum of 3&4 push 7 2 7 Pop Pop Mult of 2&7 Push 14

  30. * / + A - * * C + E + D A C B B C B A D x D y y x Converting Infix to Postfix By hand: Represent infix expression as an expression tree: A * B + C A * (B + C) ((A + B) * C) / (D - E)

  31. / / / - - - * * * E E E + + + D D D C C C A A A B B B Traverse the tree in Left-Right-Parentorder (postorder) to get Postfix: A B + C * D E - / Traverse tree in Parent-Left-Rightorder (preorder) to get prefix: / * + A B - D E C Traverse tree in Left-Parent-Rightorder (inorder) to get infix:— must insert ()'s ( ) / ( * C) (A + B) (D - E)

  32. Another PostfixConversion Method 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 + *

  33. Conversion of Infix form to Postfix Form using stack Convert the infix expression a-(b+c)*d into post fix It involves the following steps with a stack s • write a  a • push(s, -) • push(s, () • write b  ab • push(s, +) • write c  abc • finding right parenthesis pop(s, +) write it  abc+

  34. pop(s, () • push(s, *) • write d  abc+d • pop(s, *) write it  abc+d* • pop(s, -) write it  abc+d* - • Exercise • Write a function that converts an infix expression to its postfix form using a stack s and its operations given in the specification of stack ADT.

  35. Converting Infix to Equivalent Postfix A – (B + C * D) / E

  36. Parentheses Matching • (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n)

  37. Parentheses Matching • scan expression from left to right • when a left parenthesis is encountered, add its position to the stack • when a right parenthesis is encountered, remove matching position from stack

  38. Example • (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n) 2 1 0

  39. Example • (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n) 15 1 0 (2,6) (1,13)

  40. Example • (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n) 21 1 0 (2,6) (1,13) (15,19)

  41. Example • (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n) 27 1 0 (2,6) (1,13) (15,19) (21,25)

  42. Example • (((a+b)*c+d-e)/(f+g)-(h+j)*(k-l))/(m-n) 1 0 (2,6) (1,13) (15,19) (21,25) (27,31) (0,32) • and so on

  43. A LegendThe Towers of Hanoi • In the great temple of Brahma in Benares, on a brass plate under the dome that marks the center of the world, there are 64 disks of pure gold that the priests carry one at a time between these diamond needles according to Brahma's immutable law: No disk may be placed on a smaller disk. In the begging of the world all 64 disks formed the Tower of Brahma on one needle. Now, however, the process of transfer of the tower from one needle to another is in mid course. When the last disk is finally in place, once again forming the Tower of Brahma but on a different needle, then will come the end of the world and all will turn to dust.

  44. The Towers of HanoiA Stack-based Application • GIVEN: three poles • a set of discs on the first pole, discs of different sizes, the smallest discs at the top • GOAL: move all the discs from the left pole to the right one. • CONDITIONS: only one disc may be moved at a time. • A disc can be placed either on an empty pole or on top of a larger disc.

  45. Towers of Hanoi

  46. Towers of Hanoi

  47. Towers of Hanoi

  48. Towers of Hanoi

  49. Towers of Hanoi

  50. Towers of Hanoi

More Related