Stacks and queus by Juinn-Dar Huang

Stacks and queus by Juinn-Dar Huang - Data Structure...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Data Structure Chapter 3 Stacks and Queues Juinn-Dar Huang, Ph.D. Assistant Professor [email protected] August 2004 Rev. 2005, 2006 Think Them Tedious? Juinn-Dar Huang What if we want to sort an array of floats instead of ints ? Stacks and Queues [email protected] class MatrixTerm { int row, col; int value; ... Copyright © 2004-2006 What if we want to store a float instead of integer ? 1 The Savior: C++ Template Idea: Data types can also serve as parameters Juinn-Dar Huang Key to Generic Programming Generic Algorithm Stacks and Queues [email protected] Copyright © 2004-2006 Define once Use everywhere float Farr[100]; Rectangle Rarr[250]; ... sort(Farr, 100); sort(Rarr, 250); 2 Integer Bag: A Container Class (1/2) class Bag { void Full() const; // action when bag is full void Empty() const; // action when bug is empty Juinn-Dar Huang int *array; // actually a bag for int only int MaxSize; // size of array int top; // top position in array that contains an element Stacks and Queues [email protected] public: Bag(int Maxsize = DefaultSize); ~Bag(); // dtor void int* bool bool }; // ctor Add(int); // insert an int into bag Delete(int&); // delete an int from bag IsFull() const; // is the bag full? IsEmpty() const; // is the bag empty? Copyright © 2004-2006 Ignore later 3 Integer Bag: A Container Class (2/2) inline void Bag::Empty() { cerr << “Bag is empty” << endl; } Bag::~Bag() { delete array; } Juinn-Dar Huang Bag::Bag(int MSize) :MaxSize(MSize){ array = new int[MaxSize]; top = -1; } void Bag::Add(int x) { if(IsFull()) Full(); else array[++top] = x; } inline bool Bag::IsFull() { return (top == MaxSize – 1); } // must be in Bag.h Stacks and Queues [email protected] inline bool Bag::IsEmpty() { return (top == -1); } // must be in Bag.h inline void Bag::Full() { cerr << “Bag is full” << endl; } Copyright © 2004-2006 int* Bag::Delete(int& x) { if(IsEmpty()) {Empty(); return 0}; int p = top / 2; x = array[p]; for(int i = p; i < top; ++i) array[i] = array[i + 1]; --top; return &x; } 4 Bag for Any Objects (1/2) template <class T> class Bag { void Full() const; // action when bag is full void Empty() const; // action when bug is empty Juinn-Dar Huang T* array; // a bag for type T int MaxSize; // size of array int top; // top position in array that contains an element Stacks and Queues [email protected] public: Bag(int Maxsize = DefaultSize); ~Bag(); // dtor // ctor void Add(const T&); // insert a T object into bag T* Delete(T&); // delete a T object from bag bool IsFull() const; // is the bag full? bool IsEmpty() const; // is the bag empty? }; Copyright © 2004-2006 5 Bag for Any Objects (2/2) Juinn-Dar Huang template <class T> Bag<T>::Bag(int Max) :MaxSize(Max) { array = new T[MaxSize]; top = -1; } template <class T> Bag<T>::~Bag() { delete array; } Stacks and Queues [email protected] template <class T> void Bag<T>::Add(const T& x) { if(IsFull()) Full(); else array[++top] = x; } Copyright © 2004-2006 // Example Bag<int> a(100); Bag<Rectangle> r; ... 6 Stack • Stack Juinn-Dar Huang – an ordered list in which insertions and deletions are made at only one end, named the top • Given a stack S = (a0, …, an-1) – a0 is the bottom – an-1 is the top Give me examples: When do you use a stack in your daily life? Stacks and Queues [email protected] • Also named as Last-In-First Out (LIFO) Copyright © 2004-2006 7 ADT Stack (1/3) Juinn-Dar Huang template <class T> class stack { int top; T *stack; int MaxSize; one of the implementation methods there are certainly other ways to do this public: Stack(int Max = DefaultSize); ~Stack(); // dtor // ctor Stacks and Queues [email protected] bool IsFull(); bool IsEmpty(); void Add(const T& item); T* Delete(T&); // also well known as “push” // also well known as “pop” }; Copyright © 2004-2006 8 ADT Stack (2/3) Juinn-Dar Huang template <class T> Stack<T>::Stack(int Max) :MaxSize(Max) { stack = new T[MaxSize]; top = -1; } template <class T> Stack<T>::~Stack() { delete stack; } Stacks and Queues [email protected] template <class T> bool Stack<T>::IsFull() { return (top == MaxSize – 1); } template <class T> bool Stack<T>::IsEmpty() { return (top == – 1); } Copyright © 2004-2006 9 ADT Stack (3/3) Juinn-Dar Huang template <class T> void Stack<T>::Add(const T& x) { if(IsFull()) StackFull(); // StackFull() is private else stack[++top] = x; // insert from the top } Stacks and Queues [email protected] template <class T> T* Stack<T>::Delete(T& x) { if(IsEmpty()) { StackEmpty(); return 0; } // StackEmpty() is private x = stack[top--]; // delete from the top return &x; } Copyright © 2004-2006 10 Queue • Queue Juinn-Dar Huang – an ordered list in which insertions take place at one end and deletions take place at the other end • Given a queue Q = (a0, …, an-1) – a0 is the front element, delete from this end – an-1 is the rear element, insert from this end Stacks and Queues [email protected] • Also named as First-In-First Out (FIFO) Copyright © 2004-2006 11 ADT Queue (1/3) Juinn-Dar Huang template <class T> class Queue { int front, rear; one of the implementation methods T* queue; there are certainly other ways to do this int MaxSize; public: Queue(int MaxQueueSize = DefaultSize); ~Queue(); Stacks and Queues [email protected] bool IsFull(); bool IsEmpty(); void Add(const T& item); T* Delete(T&); }; Copyright © 2004-2006 12 ADT Queue (2/3) Juinn-Dar Huang template <class T> Queue<T>::Queue(int Max) :MaxSize(Max) { queue = new T[MaxSize]; front = rear = -1; } template <class T> Queue<T>::~Queue() { delete queue; } Stacks and Queues [email protected] template <class T> bool Queue<T>::IsFull() { return (rear == MaxSize – 1); } template <class T> bool Queue<T>::IsEmpty() { return (front == rear); } Copyright © 2004-2006 13 ADT Queue (3/3) Juinn-Dar Huang template <class T> void Queue<T>::Add(const T& x) { if(IsFull()) QueueFull(); // QueueFull() is private else queue[++rear] = x; // insert from the rear } Stacks and Queues [email protected] template <class T> T* Queue<T>::Delete(T& x) { if(IsEmpty()) { QueueEmpty(); return 0; } // QueueEmpty is private x = queue[++front]; // delete from the front return &x; } if (front == rear) an empty queue; or, front points to one location ahead from the head of the queue and rear points to the end of the queue Copyright © 2004-2006 14 Is the Implementation Efficient? (1/2) Juinn-Dar Huang Stacks and Queues [email protected] Copyright © 2004-2006 15 Is the Implementation Efficient? (2/2) front rear Is the queue really full ? queue Juinn-Dar Huang 0 MaxSize - 1 Move front rear Stacks and Queues [email protected] Can perform more add queue MaxSize - 1 0 This operation takes significant time Is there any better idea? Copyright © 2004-2006 16 Better Implementation (1/3) Juinn-Dar Huang Stacks and Queues [email protected] Circular queue implementation: For an array with size n, at most n-1 elements can be stored in a circular queue at the same time (Q: Why is that ?) Copyright © 2004-2006 17 Better Implementation (2/3) Juinn-Dar Huang template <class T> bool Queue<T>::IsFull() { int new_rear = (rear + 1) % MaxSize; // circular return (front == new_rear); } Stacks and Queues [email protected] template <class T> void Queue<T>::Add(const T& x) { if(IsFull()) QueueFull(); // QueueFull() is private else { rear = (rear + 1) % MaxSize; // circular queue[rear] = x; // insert from the rear } } Copyright © 2004-2006 18 Better Implementation (3/3) template <class T> T* Queue<T>::Delete(T& x) { if(IsEmpty()) Juinn-Dar Huang { QueueEmpty(); return 0; } // QueueEmpty is private front = (front + 1) % MaxSize; // circular x = queue[front]; // delete from the front return &x; } Stacks and Queues [email protected] Q: After we change the implementation of the class Queue, is it necessary to modify code fragments that utilize the class Queue? Demonstrate the power of data encapsulation ! Copyright © 2004-2006 19 Public Inheritance • C++ provides a mechanism to express the “IS-A” relationship Juinn-Dar Huang – public inheritance Base class shape polygon Stacks and Queues [email protected] rectangle Derived class square More General Polygon is a shape Rectangle is a polygon Square is a rectangle More Specialized A derived class inherits all non-private members from its base classes A derived class can also override the inherited functions for its own needs Copyright © 2004-2006 20 A Stack IS A Bag (1/2) Juinn-Dar Huang Stacks and Queues [email protected] class bag { // an int bag protected: int *array, MaxSize, top; virtual void Full(); virtual void Empty(); public: Bag(int MaxSize = DefaultSize); // ctor virtual ~Bag(); // dtor virtual void Add(int); virtual int* Delete(int&); virtual bool IsFull(); virtual bool IsEmpty(); class Stack : public Bag { }; public: Stack(int MaxSize = DefaultSize); ~Stack(); int* Delete(int &); }; Copyright © 2004-2006 21 A Stack IS A Bag (2/2) Stack::Stack(int Max) // Stack’s ctor :Bag(Max)// initialize members of base classes and its own {} // empty function body because there is nothing to do here Juinn-Dar Huang Stacks and Queues [email protected] // Bag::Delete is not appropriate for Stack override it! // That is, define its own version int* Stack::Delete(int &x) { if(IsEmpty()) {Empty(); return 0 }; x = array[top--]; // Example: return &x; Stack s(3); } s.Add(1); // invoke Bag::Add actually s.Add(2); // invoke Bag::Add actually s.Add(3); // invoke Bag::Add actually Reusability, Maintainability, Flexibility ! Copyright © 2004-2006 int x; s.Delete(x); // invoke Stack::Delete // x = ? 22 Rat in a Maze Juinn-Dar Huang Stacks and Queues [email protected] Maze map info is stored in an int array maze[m][p]. 1 represents a wall. Copyright © 2004-2006 23 Make a Move Juinn-Dar Huang Stacks and Queues [email protected] struct offsets { int a, b; } enum { N, NE, E, SE, S, SW, W, NW }; offsets move[8]; move one step southwest from [i][j] to [g][h] g = i + move[SW].a; h = j + move[SW].b; Copyright © 2004-2006 24 How to Find a Path? • Idea Juinn-Dar Huang – at each location, we try all possible directions starting from the north and try other directions clockwise – when I find a legal move, to prevent running into a deadend, I save the current position and my heading direction into a stack – I won’t trace the same path twice Stacks and Queues [email protected] • use an array mark[m][p] to record whether I’ve visited here or not – When I cannot find any legal move at a location, I backtrack one step • how? remember the stack? – when I finally reach the exit, how did I make it? • once again, think about the stack Copyright © 2004-2006 25 Path Finding Algorithm maze, mark, move are all global arrays Juinn-Dar Huang Touch down Stacks and Queues [email protected] Optimize ? one copy? Stack stores the next possible move // end of inner while // end of outer while Copyright © 2004-2006 There is no way out; we are fooled 26 Detailed Path Finding Algorithm • Define the record for later backtrack Juinn-Dar Huang struct items { int x, y, dir; }; • Check Program 3.16 @ p145 Stacks and Queues [email protected] must be a friend of class Stack Copyright © 2004-2006 its type is items ??? 27 Arithmetic Expression • An arithmetic expression – X=A/B–C+D*E–A*C Juinn-Dar Huang • Does it imply – X = (((A / B) – C) + (D * E)) – (A * C) ?, or – X = ((X / (B – C + D)) * (E – A )) * C ? Stacks and Queues [email protected] • Precedence table in C/C++ (partial) • Use parentheses to override the original priority – that is, parentheses has the first priority in fact – e.g., A / (B – C) Copyright © 2004-2006 priority operator ================== 1 unary minus, ! 2 *, /, % 3 +, – 4 <. <=, >, >= 5 ==, != 6 && 7 || 28 Infix vs. Postfix • Infix notation Juinn-Dar Huang – the operator is in-between the operands – e.g., A + B • Postfix notation – the operator appears after the operands – e.g., A B + Stacks and Queues [email protected] • Why postfix notation? – parentheses-free ! – e.g., A * (B + C) ABC+* infix postfix – e.g., A/B–C+D*E–A*C Copyright © 2004-2006 AB/C–DE*+AC*– 29 Evaluate Postfix Expressions Evaluate a postfix expression AB/C–DE*+AC*– Juinn-Dar Huang Stacks and Queues [email protected] operation operator ====================================== T1 = A / B T1C–DE*+AC*– T2 = T1 – C T2 DE*+AC*– T3 = D * E T2T3+AC*– T4 = T2 + T3 T4AC*– T5 = A * C T4T5– T6 = T4 – T5 T6 Q: How to efficiently implement these operations? Copyright © 2004-2006 30 Postfix Expression Evaluation Juinn-Dar Huang Stacks and Queues [email protected] A: No kidding! It’s stack again Copyright © 2004-2006 31 From Infix to Postfix • 3 steps Juinn-Dar Huang – fully parenthesize the expression – move all operators so that they replace their corresponding right parentheses – delete all parentheses • Example: A / B – C + D * E – A * C Stacks and Queues [email protected] – ( ( ( ( A / B ) – C ) + ( D * E ) ) – ( A * C ) ) – ( ( ( ( A B / C – ( D E * + A C * – – A B / C – D E * + A C * – This is the way for human being Q: What is the efficient way for computer? Copyright © 2004-2006 32 Inside Look • Observation 1 Juinn-Dar Huang – the order of the operands is the same in both infix and postfix • Observation 2 – A*B–C – A–B*C AB*C– ABC*– Why is that? Stacks and Queues [email protected] • The reason is the precedence Hint • Q: How to implement it? – yea, it’s me again, stack! Copyright © 2004-2006 priority operator ================== 1 unary minus, ! 2 *, /, % 3 +, – 4 <. <=, >, >= 5 ==, != 6 && 7 || 33 Translation via Stack Operations (1/2) • Rules Juinn-Dar Huang – scan the infix expression from left to right – if the token is an operand, output it immediately – if the token is an operator Stacks and Queues [email protected] Copyright © 2004-2006 • if its priority is higher than that of the top (of the stack) – push the operator into the stack • if its priority is equal or lower than that of the top – repeat popping the stack and outputting the operators until its priority is higher than that of the new top – push the operator into the stack 34 Translation via Stack Operations (2/2) Example: A*(B+C)/D in-stack priority in-coming priority Juinn-Dar Huang Stacks and Queues [email protected] isp icp operator ========================= 0 ( 1 1 unary minus, ! 2 2 *, /, % 3 3 +, – 4 4 <. <=, >, >= 5 5 ==, != 6 6 && 7 7 || 8 (,# next token stack output H =============================== none # none A # A * #* A ( #*( A B #*( AB + #*(+ AB L C #*(+ ABC ) #* ABC+ // pop until ( #: end of expression / #/ ABC+* D #/ ABC+*D done ABC+*D/# // empty the stack Copyright © 2004-2006 35 Algorithm: From Infix to Postfix Juinn-Dar Huang Stacks and Queues [email protected] Copyright © 2004-2006 Θ(length of e) 36 Final Review • Container class Bag • Stack (LIFO) Juinn-Dar Huang – applications • maze solver, postfix expression evaluation, and infix to postfix • Queue (FIFO) – circular queue Stacks and Queues [email protected] • C++ features – template • type as parameter • generic programming – inheritance • public inheritance represents the “IS-A” relationship Copyright © 2004-2006 37 C++ Reference • Check C++ STL for following container classes Juinn-Dar Huang – stack – queue – deque Stacks and Queues [email protected] Copyright © 2004-2006 38 ...
View Full Document

This note was uploaded on 05/25/2010 for the course CPE CPE 360 taught by Professor Jenniferchen during the Spring '10 term at Stevens.

Ask a homework question - tutors are online