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

Slides:



Advertisements
Similar presentations
Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can be instantiated.
Advertisements

CSCE 3110 Data Structures & Algorithm Analysis Stacks and Queues Reading: Chap.3 Weiss.
CS Data Structures ( 資料結構 ) Chapter 3: Stacks and Queues Spring 2012.
Stacks Chapter 11.
C o n f i d e n t i a l Developed By Nitendra NextHome Subject Name: Data Structure Using C Title : Overview of Stack.
CSCE 3110 Data Structures & Algorithm Analysis Queues Reading: Chap. 3 Weiss.
Chapter 3 1. Templates in C++ Template function in C++ makes it easier to reuse classes and functions. A template can be viewed as a variable that can.
 Chapter 7 introduces the stack data type.  Several example applications of stacks are given in that chapter.  This presentation shows another use called.
Stacks CS 3358 – Data Structures. What is a stack? It is an ordered group of homogeneous items of elements. Elements are added to and removed from the.
P Chapter 6 introduces the stack data type. p Several example applications of stacks are given in that chapter. p This presentation shows another use called.
The N-Queens Problem lab01.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Part-B1 Stacks. Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
CSC212 Data Structure - Section FG Lecture 12 Stacks and Queues Instructor: Zhigang Zhu Department of Computer Science City College of New York.
Stacks  Standard operations: IsEmpty … return true iff stack is empty Top … return top element of stack Push … add an element to the top of the stack.
Stacks Linear list. One end is called top. Other end is called bottom. Additions to and removals from the top end only.
Stacks CSE, POSTECH. 2 2 Stacks Linear list One end is called top. Other end is called bottom. Additions to and removals from the top end only.
The Stack and Queue Types Lecture 10 Hartmut Kaiser
Stack  A stack is a linear data structure or abstract data type for collection of items, with the restriction that items can be added one at a time and.
Data Structures Using C++ 2E Chapter 6 Recursion.
Fundamentals of Python: From First Programs Through Data Structures Chapter 14 Linear Collections: Stacks.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
Chapter 7 Stacks Dr. Youssef Harrath
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Review 1 Introduction Representation of Linear Array In Memory Operations on linear Arrays Traverse Insert Delete Example.
Data Structures Using C++ 2E Chapter 6 Recursion.
SAK 3117 Data Structures Chapter 3: STACKS. Objective To introduce: Stack concepts Stack operations Stack applications CONTENT 3.1 Introduction 3.2 Stack.
DATA STRUCTURE & ALGORITHMS CHAPTER 3: STACKS. 2 Objectives In this chapter, you will: Learn about stacks Examine various stack operations Discover stack.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Stacks 1. Stack  What is a stack? An ordered list where insertions and deletions occur at one end called the top. Also known as last-in-first-out (LIFO)
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
Stacks Chapter 8. Objectives In this chapter, you will: Learn about stacks Examine various stack operations Learn how to implement a stack as an array.
For more notes and topics VISIT: IMPLEMENTATION OF STACKS eITnotes.com.
1 CS 132 Spring 2008 Chapter 7 Stacks Read p Problems 1-7.
CHAPTER 3 STACK CSEB324 DATA STRUCTURES & ALGORITHM.
Applications of Stacks and Queues Stacks Linear list. One end is called top. Other end is called bottom. Additions to and removals from the top end only.
 STACK STACK  STACK OPERATIONS STACK OPERATIONS  PUSH ALGORITHM PUSH ALGORITHM  POP ALGORITHM POP ALGORITHM  USES OF STACK USES OF STACK  THE TOWER.
Stacks Nour El-Kadri CSI Stacks Software stacks are abstract data types (structures) similar to physical stacks, Plates Trays Books PEZ dispenser.
CHP-3 STACKS.
1 CSC 222: Computer Programming II Spring 2004 Stacks and recursion  stack ADT  push, pop, top, empty, size  vector-based implementation, library 
Stacks & Queues. Introduction to Stacks and Queues Widely used data structures Ordered List of element Easy to implement Easy to use.
Stacks Linear list. One end is called top. Other end is called bottom. Additions to and removals from the top end only.
Prof. I. J. Chung Data Structure #5 Professor I. J. Chung.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
1 Data Structures and Algorithms Stack. 2 The Stack ADT Introduction to the Stack data structure Designing a Stack class using dynamic arrays Linked Stacks.
 Chapter 7 introduces the stack data type.  Several example applications of stacks are given in that chapter.  This presentation shows another use called.
ADT Stack What Is a Stack? Standard Template Library Stack Class
CSCE 3110 Data Structures & Algorithm Analysis
Chapter 4 Stacks
CS Data Structures Chapter 6 Stacks Mehmet H Gunes
Stacks.
Stacks Stacks.
Stacks Linear list. One end is called top. Other end is called bottom.
Stacks.
STACKS AND QUEUES UNIT 2 DS THROUGH C++.
Stacks.
STACKS.
Stacks Chapter 4.
Algorithms and Data Structures
Stack.
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks.
Stacks.
Stack.
Presentation transcript:

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 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.

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

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

Last In First Out BABA DCBADCBA CBACBA DCBADCBA EDCBAEDCBA top A

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

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)

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

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.

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

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)

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

Implementation of Stack by Array a0a0 a1a1 a2a2 Array index 0123n-1 a0a0 a1a1 a2a2 a n-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 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

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 };

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

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

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

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; } abcde top

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

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

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

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

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*+

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

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.

Postfix evaluation - Example Expression Code Stack Contents <> * push 3 ^ push 5 add * push 8 ^ push 6 sub * mul ^

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 * 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

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

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

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

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+

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.

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

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

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

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

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

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

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

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

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.

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.

Towers of Hanoi

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); }

Rat In A Maze

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

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

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

Rat In A Maze Move down.

Rat In A Maze Move left.

Rat In A Maze Move down.

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

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

Rat In A Maze Move right. Backtrack.

Rat In A Maze Move downward.

Rat In A Maze Move right.

Rat In A Maze Move one down and then right.

Rat In A Maze Move one up and then right.

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

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

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

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

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

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

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

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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...

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.

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.

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.

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.