Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stacks and Queues. Sample PMT online… Browse 1120/sumII05/PMT/2004_1/

Similar presentations


Presentation on theme: "Stacks and Queues. Sample PMT online… Browse 1120/sumII05/PMT/2004_1/"— Presentation transcript:

1 Stacks and Queues

2 Sample PMT online… Browse http://www.cs.wmich.edu/gupta/teaching/cs 1120/sumII05/PMT/2004_1/ http://www.cs.wmich.edu/gupta/teaching/cs 1120/sumII05/PMT/2004_1/

3 Queue ADT A queue is a FIFO: first in, first out

4 Application: Recognizing Palindromes Palindrome is a string of characters that reads the same from left to right as it does from right to left –Madam, I’m Adam –A man, a plan, a canal, Panama

5 Example

6 Pseudocode aQueue.createQueue(); aStack.createStack(); while (not end){ cin >> ch; aQueue.enqueue(ch); aStack.push(ch); } isPal = true; While(!aQueue.isEmpty() && isPal){ c1 = aQueue.getFront(); c2 = aStack.getTop(); if (c1==c2){ aQueue.dequeue(); aStack.pop(); } else { isPal = false; }

7 Array-Based Q Implementation class Queue { public: … private: QueueItem items[MAX_QUEUE]; int front, back; };

8 Problem with Array-based Implementation Rightward shift –Queue is full even if it contains few items! Solution: shift array items to the left –It would dominate the cost of implementation. Any good idea?

9 Solution View array as circular

10 How to Insert and Remove? enqueue() –Move back index clockwise dequeue() –Move front index clockwise

11 Special Cases Queue has one item front==back Queue is empty front is one item ahead ( front == (back+1)%MAX_QUEUE )

12 Special Cases When queue is full –front is one item ahead, again??

13 Distinguish Between Empty and Full Keep a count of the number of items Before enqueue, check if count == MAX_QUEUE Before dequeue, check if count==0 class Queue { public: … private: QueueItem items[MAX]; int front, back; int count; };

14 Array-Based Implementation item Queue::getFront(){ if (isEmpty()) exit(0); else return items[front]; } void Queue::Queue() :front(0), back(MAX-1), count(0) { } bool Queue::isEmpty(){ return (count==0); }

15 Array-Based Implementation void Queue::dequeue(){ if (isEmpty()) exit(0); else{ front =(front+1)%MAX; --count; } void Queue::enqueue(Item newItem) { if (count==MAX) exit(0); else { back = (back+1)%MAX; items[back] = newItem; ++count; }

16 ADT List-Based Implementation class Queue { public: … private: List aList; };

17 ADT List-Based Implementation Queue::Queue (const Queue& Q) :aList(Q.aList){} bool Queue::isEmpty(){ return aList.isEmpty(); } void Queue::getFront(){ if (aList.isEmpty()) exit(0); return (aList.retrieve(1)); }

18 ADT List-Based Implementation void Queue::enqueue(){ aList.insert(aList.getLength()+1, newItem); } void Queue::dequeue(){ if (aList.isEmpty()) exit(0); aList.remove(1); }

19 Templates

20 The Items in ADTs class List { public: … private: Item items[MAX]; }; class Queue { public: … private: Item items[MAX]; }; class Stack { public: … private: Item items[MAX]; }; We have to substitute Item with concrete types

21 How to Use ADT with Different Item Types? If we need only one integer list in our program –“typedef int Item;” What if we need two lists: a list of real numbers and a list of characters? class RealList { private: float items[MAX]; }; class CharList { private: char items[MAX]; };

22 Similar Redundancy in Functions Recall function swapValues void swapValues(int& var1, int& var2) { int temp; temp = var1; var1 = var2; var2 = temp; } Applies only to variables of type int, but code would work for any types! void swapValues(char& var1, char& var2) { char temp; temp = var1; var1 = var2; var2 = temp; }

23 Avoid Redundancy by Templates C++ templates –Allow very ‘general’ definitions for functions and classes –Type names are ‘parameters’ instead of actual types –Precise definition determined at run-time

24 Function Template Syntax Allow swap values of any type variables template void swapValues(T& var1, T& var2) { T temp; temp = var1; var1 = var2; var2 = temp; } First line called ‘template prefix’ –Tells compiler what’s coming is ‘template’ –And that T is a type parameter

25 Template Prefix Recall: template In this usage, ‘class’ means ‘type’, or ‘classification’ Can be confused with other ‘known’ use of word ‘class’! –C++ allows keyword ‘typename’ in place of keyword ‘class’ here –But most use ‘class’ anyway

26 Template Prefix 2 Again: template T can be replaced by any type –Predefined or user-defined (like a C++ class type) In function definition body: –T used like any other type –Note: can use other than ‘T’, but T is ‘traditional’ usage

27 Calling a Function Template Consider following call: swapValues(int1, int2); C++ compiler ‘generates’ function definition for two int parameters using template Likewise for all other types Needn’t do anything ‘special’ in call –Required definition automatically generated

28 Another Function Template Declaration: template void showStuff(int s1, T s2, T s3); Definition: Template void showStuff(int s1, T s2, T s3) { cout << s1 << endl << s2 << endl << s3 << endl; }

29 showStuff Call Consider function call: showStuff(2, 3.3, 4.4); Compiler generates function definition –Replaces T with double Since second parameter is type double Displays: 2 3.3 4.4

30 Multiple Type Parameters Can have: template Not typical –Usually only need one ‘replaceable’ type –Cannot have ‘unused’ template parameters Each must be ‘used’ in definition Error otherwise!

31 Defining Templates Strategies Develop function normally –Using actual data types Completely debug ‘ordinary’ function Then convert to template –Replace type names with type parameter as needed Advantages: –Easier to solve ‘concrete’ case –Deal with algorithm, not template syntax

32 Inappropriate Types in Templates Can use any type in template for which code makes ‘sense’ –Code must behave in appropriate way e.g.: swapValues() template function –Cannot use type for which assignment operator isn’t defined –int a[10], b[10]; swapValues(a, b);

33 Class Templates Can also ‘generalize’ classes –template can apply to class definition –All instances of ‘T’ in class definition replaced by type parameter –Just like for function templates! Once template defined, can declare objects of the class

34 Class Template Definition template class NewClass{ public: NewClass(); NewClass(T init); void setData(T nD); T getData(); private: T theData; };

35 Member Function Definitions template NewClass ::NewClass() {} template NewClass ::NewClass(T init): theData(init) {} template void NewClass ::setData(T nD){ theData = nD; } template T NewClass ::getData() { return theData; }

36 Member Function Definitions Notice in member function definitions: –Each definition is itself a ‘template’ –Requires template prefix before each definition –Class name before :: is ‘NewClass ’ Not just ‘NewClass’ –But constructor name is just ‘NewClass’ –Destructor name is also just ‘~NewClass’

37 Class Template Usage int main(){ NewClass a(5); NewClass b; b.setData(1.5678); cout << a.getData(); };

38 Class Template Be careful about what you do with objects of type T within the template class template void NewClass ::display() { cout << theData; }; display() is correct if T is standard types such as int, char, string –What if T is user-defined?

39 Restrictions on Type Parameter Only ‘reasonable’ types can be substituted for T Consider: –Assignment operator must be ‘well-behaved’ –Copy constructor must also work –If T involves pointers, then destructor must be suitable! Similar issues as function templates

40 Type Definitions Can define new ‘class type name’ –To represent specialized class template name Example: typedef NewClass NewClassOfInt; Name ‘NewClassOfInt’ now used to declare objects of type NewClass : NewClassOfInt n1, n2; Name can also be used as parameter, or anywhere else type name allowed

41 Stack Revisited – dynamic array based implementation template class Stack { public: Stack(int s); ~Stack(){delete [] stackPtr}; bool push(const T&); bool pop(T&); private: int size; int top; T *stackPtr; bool isEmpty() const {return top==-1}; bool isFull()const {return top==size-1;} };

42 Stack Revisited template Stack ::Stack(int s) { size = s>0 ? s : 10; top = -1; stackPtr = new T[size]; } template bool Stack ::push(const T &pushValue) { if (!isFull()) { stackPtr[++top] = pushValue; return true; } return false; }

43 Stack Usage int main() { Stack dStack(5); double f=1.1; while(dStack.push(f)) f+=1.1; while(dStack.pop(f)) cout << f <<endl; return 0; }


Download ppt "Stacks and Queues. Sample PMT online… Browse 1120/sumII05/PMT/2004_1/"

Similar presentations


Ads by Google