96
Data Structure Dr. Mohamed Khafagy

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

Embed Size (px)

Citation preview

  • Slide 1
  • Data Structure Dr. Mohamed Khafagy
  • Slide 2
  • Stacks Stack: what is it? ADT Applications Implementation(s)
  • Slide 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.
  • Slide 4
  • Stacks (2) A PEZ dispenser as an analogy:
  • Slide 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
  • Slide 6
  • Last In First Out BABA DCBADCBA CBACBA DCBADCBA EDCBAEDCBA top A
  • Slide 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
  • Slide 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)
  • Slide 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
  • Slide 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.
  • Slide 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
  • Slide 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 (contd)
  • Slide 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
  • Slide 14
  • Implementation of Stack by Array a0a0 a1a1 a2a2 Array index 0123n-1 a0a0 a1a1 a2a2 a n-1
  • Slide 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
  • Slide 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 };
  • Slide 17
  • Constructor template Stack ::Stack(int stackCapacity) :capacity(stackCapacity) { if (capacity < 1) throw Stack capacity must be > 0; stack = new T[capacity]; top = -1; }
  • Slide 18
  • IsEmpty template inline bool Stack ::IsEmpty() const {return top == -1}
  • Slide 19
  • Top template inline T& Stack ::Top() const { if (IsEmpty()) throw Stack is empty; return stack[top]; }
  • Slide 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 item = item; temp->next= top; top= temp; } List-based Stack Implementation: Push">
  • 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
  • Slide 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
  • Slide 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
  • Slide 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*+
  • Slide 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
  • Slide 27
  • Postfix notation Widely used in real compilers for programming languages. The programmers 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.
  • Slide 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 ^
  • Slide 29
  • for ( (c = cin.get( )) != \n) { if ( c >= 0 && c = 1) { hanoi(discs-1, fromPo">
  • 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); }
  • Slide 54
  • Rat In A Maze
  • Slide 55
  • Move order is: right, down, left, up Block positions to avoid revisit.
  • Slide 56
  • Rat In A Maze Move order is: right, down, left, up Block positions to avoid revisit.
  • Slide 57
  • Rat In A Maze Move backward until we reach a square from which a forward move is possible.
  • Slide 58
  • Rat In A Maze Move down.
  • Slide 59
  • Rat In A Maze Move left.
  • Slide 60
  • Rat In A Maze Move down.
  • Slide 61
  • Rat In A Maze Move backward until we reach a square from which a forward move is possible.
  • Slide 62
  • Rat In A Maze Move backward until we reach a square from which a forward move is possible. Move downward.
  • Slide 63
  • Rat In A Maze Move right. Backtrack.
  • Slide 64
  • Rat In A Maze Move downward.
  • Slide 65
  • Rat In A Maze Move right.
  • Slide 66
  • Rat In A Maze Move one down and then right.
  • Slide 67
  • Rat In A Maze Move one up and then right.
  • Slide 68
  • Rat In A Maze Move down to exit and eat cheese. Path from maze entry to current position operates as a stack.
  • Slide 69
  • The N-Queens Problem Suppose you have 8 chess queens......and a chess board
  • Slide 70
  • The N-Queens Problem Can the queens be placed on the board so that no two queens are attacking each other ?
  • Slide 71
  • The N-Queens Problem Two queens are not allowed in the same row...
  • Slide 72
  • The N-Queens Problem Two queens are not allowed in the same row, or in the same column...
  • Slide 73
  • The N-Queens Problem Two queens are not allowed in the same row, or in the same column, or along the same diagonal.
  • Slide 74
  • The N-Queens Problem The number of queens, and the size of the board can vary. N Queens N rows N columns
  • Slide 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.
  • Slide 76
  • How the program works The program uses a stack to keep track of where each queen is placed.
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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
  • Slide 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...
  • Slide 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.
  • Slide 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.
  • Slide 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.
  • Slide 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.