Presentation is loading. Please wait.

Presentation is loading. Please wait.

Data Structure Dr. Mohamed Khafagy. Stacks Stack: what is it? ADT Applications Implementation(s)

Similar presentations


Presentation on theme: "Data Structure Dr. Mohamed Khafagy. Stacks Stack: what is it? ADT Applications Implementation(s)"— 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 Stack Of Cups Add a cup to the stack. bottom top C A B D E F Remove a cup from new stack. A stack is a LIFO list. bottom top C A B D E

6 Last In First Out BABA DCBADCBA CBACBA DCBADCBA EDCBAEDCBA top A

7 Stack (Cont.) Given a stack S = (a 0, …, a n-1 ), a 0 is the bottom element, a n-1 is the top element, and a i is on top of element a i-1, 0 < i < n. a0a0 a1a1 a2a2 Push (Add) a0a0 a1a1 a2a2 Pop (Delete) a3a3 a3a3

8 Exercise: Stacks Describe the output of the following series of stack operations Push(8) Push(3) Pop() Push(2) Push(5) 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 integer Stack createS(max_stack_size) ::= create an empty stack whose maximum size is max_stack_size Boolean isFull(stack, max_stack_size) ::= if (number of elements in stack == max_stack_size) return TRUE else return FALSE Stack push(stack, item) ::= if (IsFull(stack)) stack_full else insert item into top of stack and return objects: a finite ordered list with zero or more elements. methods: for all stack  Stack, item  element, max_stack_size  positive integer Stack createS(max_stack_size) ::= create an empty stack whose maximum size is max_stack_size Boolean isFull(stack, max_stack_size) ::= if (number of elements in stack == max_stack_size) return TRUE else return FALSE Stack push(stack, item) ::= if (IsFull(stack)) stack_full else insert item into top of stack and return Stack ADT

12 Boolean isEmpty(stack) ::= if(stack == CreateS(max_stack_size)) return TRUE else return FALSE Element pop(stack) ::= if(IsEmpty(stack)) return else 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 a0a0 a1a1 a2a2 Array index 0123n-1 a0a0 a1a1 a2a2 a n-1

15 Stack createS(max_stack_size) ::= #define MAX_STACK_SIZE 100 /* maximum stack size */ typedef struct { int key; /* other fields */ } element; element stack[MAX_STACK_SIZE]; int top = -1; Boolean isEmpty(Stack) ::= top = MAX_STACK_SIZE-1; Stack createS(max_stack_size) ::= #define MAX_STACK_SIZE 100 /* maximum stack size */ typedef struct { int key; /* other fields */ } element; element stack[MAX_STACK_SIZE]; int top = -1; Boolean isEmpty(Stack) ::= top = MAX_STACK_SIZE-1; Stack Implementation: CreateS, isEmpty, isFull

16 The Class Stack template class Stack { public: Stack(int stackCapacity = 10); ~Stack() {delete [] stack;} bool IsEmpty() 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 Stack ::Stack(int stackCapacity) :capacity(stackCapacity) { if (capacity < 1) throw “Stack capacity must be > 0”; stack = new T[capacity]; top = -1; }

18 IsEmpty template inline bool Stack ::IsEmpty() const {return top == -1}

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

20 Push template void Stack ::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; } 01234 abcde top

21 Pop void Stack ::Pop() { if (IsEmpty()) throw “Stack is empty. Cannot delete.”; stack[top--].~T(); // destructor for T } 01234 abcde top

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 ^ push 5 add 3 5 + 8 6 - * push 8 ^ push 6 sub 3 5 + 8 6 - * mul ^

29 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; } Assumptions:syntactically correct, no unary operations, and single digit operands 2 3 4 + * OperationsStack push 2:2 push 3:2 3 push 4:2 3 4 pop2 3 pop2 Sum of 3&4 push 72 7 Pop Mult of 2&7 Push14

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

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

32 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) ) Another PostfixConversion Method

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 ChStackpostFixExpRemark AAPostfix += A --APush - (-(APush ( B-(A BPostfix += B +-(+A BPush + C-(+A B CPostfix += C *-(+*A B CPush * where pr(*) > pr(- ) D-(+*A B C DPostfix += D )-(+A B C D *Pop *, Postfix += * -(A B C D * +Pop +, Postfix += + -A B C D * +Pop ( /-/A B C D * +Push / where pr(/) > pr(-) E-/A B C D * + EPostfix += E A B C D * + E / - 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) 0 1 2

39 Example 0 1 (2,6)(1,13) 15

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

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

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

43 A Legend The 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 Hanoi A 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

47

48

49

50

51

52

53 Towers of Hanoi – Recursive Solution void hanoi (int discs, Stack fromPole, Stack toPole, Stack aux) { Disc d; if( discs >= 1) { hanoi(discs-1, fromPole, aux, toPole); d = fromPole.pop(); toPole.push(d); hanoi(discs-1,aux, toPole, fromPole); }

54 Rat In A Maze

55 Move order is: right, down, left, up Block positions to avoid revisit.

56 Rat In A Maze Move order is: right, down, left, up Block positions to avoid revisit.

57 Rat In A Maze Move backward until we reach a square from which a forward move is possible.

58 Rat In A Maze Move down.

59 Rat In A Maze Move left.

60 Rat In A Maze Move down.

61 Rat In A Maze Move backward until we reach a square from which a forward move is possible.

62 Rat In A Maze Move backward until we reach a square from which a forward move is possible. Move downward.

63 Rat In A Maze Move right. Backtrack.

64 Rat In A Maze Move downward.

65 Rat In A Maze Move right.

66 Rat In A Maze Move one down and then right.

67 Rat In A Maze Move one up and then right.

68 Rat In A Maze Move down to exit and eat cheese. Path from maze entry to current position operates as a stack.

69 The N-Queens Problem Suppose you have 8 chess queens......and a chess board

70 The N-Queens Problem Can the queens be placed on the board so that no two queens are attacking each other ?

71 The N-Queens Problem Two queens are not allowed in the same row...

72 The N-Queens Problem Two queens are not allowed in the same row, or in the same column...

73 The N-Queens Problem Two queens are not allowed in the same row, or in the same column, or along the same diagonal.

74 The N-Queens Problem The number of queens, and the size of the board can vary. N Queens N rows N columns

75 The N-Queens Problem We will write a program which tries to find a way to place N queens on an N x N chess board.

76 How the program works The program uses a stack to keep track of where each queen is placed.

77 How the program works Each time the program decides to place a queen on the board, the position of the new queen is stored in a record which is placed in the stack. ROW 1, COL 1

78 How the program works We also have an integer variable to keep track of how many rows have been filled so far. ROW 1, COL 1 1 filled

79 How the program works Each time we try to place a new queen in the next row, we start by placing the queen in the first column... ROW 1, COL 1 1 filled ROW 2, COL 1

80 How the program works...if there is a conflict with another queen, then we shift the new queen to the next column. ROW 1, COL 1 1 filled ROW 2, COL 2

81 How the program works If another conflict occurs, the queen is shifted rightward again. ROW 1, COL 1 1 filled ROW 2, COL 3

82 How the program works When there are no conflicts, we stop and add one to the value of filled. ROW 1, COL 1 2 filled ROW 2, COL 3

83 How the program works Let's look at the third row. The first position we try has a conflict... ROW 1, COL 1 2 filled ROW 2, COL 3 ROW 3, COL 1

84 How the program works...so we shift to column 2. But another conflict arises... ROW 1, COL 1 2 filled ROW 2, COL 3 ROW 3, COL 2

85 How the program works...and we shift to the third column. Yet another conflict arises... ROW 1, COL 1 2 filled ROW 2, COL 3 ROW 3, COL 3

86 How the program works...and we shift to column 4. There's still a conflict in column 4, so we try to shift rightward again... ROW 1, COL 1 2 filled ROW 2, COL 3 ROW 3, COL 4

87 How the program works...but there's nowhere else to go. ROW 1, COL 1 2 filled ROW 2, COL 3 ROW 3, COL 4

88 How the program works When we run out of room in a row: pop the stack, reduce filled by 1 and continue working on the previous row. ROW 1, COL 1 1 filled ROW 2, COL 3

89 How the program works Now we continue working on row 2, shifting the queen to the right. ROW 1, COL 1 1 filled ROW 2, COL 4

90 How the program works This position has no conflicts, so we can increase filled by 1, and move to row 3. ROW 1, COL 1 2 filled ROW 2, COL 4

91 How the program works In row 3, we start again at the first column. ROW 1, COL 1 2 filled ROW 2, COL 4 ROW 3, COL 1

92 Pseudocode for N-Queens  Initialize a stack where we can keep track of our decisions.  Place the first queen, pushing its position onto the stack and setting filled to 0.  repeat these steps ◦ if there are no conflicts with the queens... ◦ else if there is a conflict and there is room to shift the current queen rightward... ◦ else if there is a conflict and there is no room to shift the current queen rightward...

93 Pseudocode for N-Queens  repeat these steps ◦ if there are no conflicts with the queens... Increase filled by 1. If filled is now N, then the algorithm is done. Otherwise, move to the next row and place a queen in the first column.

94 Pseudocode for N-Queens  repeat these steps ◦ if there are no conflicts with the queens... ◦ else if there is a conflict and there is room to shift the current queen rightward... Move the current queen rightward, adjusting the record on top of the stack to indicate the new position.

95 Pseudocode for N-Queens  repeat these steps ◦ if there are no conflicts with the queens... ◦ else if there is a conflict and there is room to shift the current queen rightward... ◦ else if there is a conflict and there is no room to shift the current queen rightward... Backtrack! Keep popping the stack, and reducing filled by 1, until you reach a row where the queen can be shifted rightward. Shift this queen right.

96 Pseudocode for N-Queens  repeat these steps ◦ if there are no conflicts with the queens... ◦ else if there is a conflict and there is room to shift the current queen rightward... ◦ else if there is a conflict and there is no room to shift the current queen rightward... Backtrack! Keep popping the stack, and reducing filled by 1, until you reach a row where the queen can be shifted rightward. Shift this queen right.


Download ppt "Data Structure Dr. Mohamed Khafagy. Stacks Stack: what is it? ADT Applications Implementation(s)"

Similar presentations


Ads by Google