Presentation is loading. Please wait.

Presentation is loading. Please wait.

Prof. Qing Wang Lecture 5 Stack and Queue Lecture Notes: Data Structures and Algorithms.

Similar presentations


Presentation on theme: "Prof. Qing Wang Lecture 5 Stack and Queue Lecture Notes: Data Structures and Algorithms."— Presentation transcript:

1 Prof. Qing Wang Lecture 5 Stack and Queue Lecture Notes: Data Structures and Algorithms

2 Software College, Northwestern Polytechnical Univ. 2Prof. Q.Wang Chapter 5-1 Stacks Table of Contents –Stack SpecificationsStack Specifications –ADT Stacks and Their ImplementationsADT Stacks and Their Implementations –Application 1: Bracket MatchingApplication 1: Bracket Matching –Application 2: A Desk CalculatorApplication 2: A Desk Calculator –Application 3: Infix Expression to PostfixApplication 3: Infix Expression to Postfix –SummarySummary Queue

3 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 3Prof. Q.Wang 5-1.1 Stacks Definition –A stack is a kind of special linear list. –A stack is a data structure in which all insertions and removals of entries are made at one end, called the top of the stack. –LIFO structure: The last entry which was inserted is the first one that will be removed. (Last in first out)

4 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 4Prof. Q.Wang Example

5 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 5Prof. Q.Wang Concepts Top –The specific end of linear list at which elements can inserted and removed. Bottom –Another end of the stack. Insertion (Push) Removal (Pop)

6 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 6Prof. Q.Wang Examples of Push and Pop

7 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 7Prof. Q.Wang

8 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 8Prof. Q.Wang 5-1.2 ADT of Stacks template class Stack { public: Stack ( int=10 ); void Push ( const Type & item); Type Pop ( ); Type GetTop ( ); void MakeEmpty ( ); int IsEmpty ( ) const; int IsFull ( ) const; }

9 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 9Prof. Q.Wang #include template class Stack { public: Stack ( int=10 ); ~Stack ( ) { delete [ ] elements; } void Push ( const Type & item ); Type Pop ( ); Type GetTop ( ); void MakeEmpty ( ) { top = - 1; } int IsEmpty ( ) const { return top == - 1; } int IsFull ( ) const { return top == maxSize - 1; } Sequential Stack Implementation

10 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 10Prof. Q.Wang private: int top; Type *elements; int maxSize; } template Stack :: Stack ( int s ) : top ( - 1), maxSize (s) { elements = new Type[maxSize]; assert ( elements != 0 ); }

11 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 11Prof. Q.Wang Push Demo

12 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 12Prof. Q.Wang Pop Demo

13 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 13Prof. Q.Wang template void Stack :: Push ( const Type & item ) { assert ( !IsFull ( ) ); elements[++top] = item; } template Type Stack :: Pop ( ) { assert ( !IsEmpty ( ) ); return elements[top--]; } template Type stack :: GetTop ( ) { assert ( !IsEmpty ( ) ); return elements[top]; }

14 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 14Prof. Q.Wang Linked Stack Implementation template class Stack; template class StackNode { friend class Stack ; private: Type data; StackNode *link; StackNode ( Type d = 0, StackNode *l = NULL ) : data ( d ), link ( l ) { } };

15 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 15Prof. Q.Wang template class Stack { public: Stack ( ) : top ( NULL ) { } ~Stack ( ); void Push ( const Type & item); Type Pop ( ); Type GetTop ( ); void MakeEmpty ( ); int IsEmpty ( ) const { return top == NULL; } private: StackNode *top; }

16 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 16Prof. Q.Wang template Stack :: ~Stack ( ) { StackNode *p; while ( top != NULL ) { p = top; top = top→link; delete p; } } template void Stack :: Push ( const Type &item ) { top = new StackNode ( item, top ); }

17 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 17Prof. Q.Wang template Type Stack :: Pop ( ) { assert ( !IsEmpty ( ) ); StackNode *p = top; Type retvalue = p→data; top = top→link; delete p; return retvalue; } template Type Stack :: GetTop ( ) { assert ( !IsEmpty ( ) ); return top→data; }

18 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 18Prof. Q.Wang Question? Two stacks shared in the same array. –Initialization. –Push entry into stack 1 or stack 2. –Pop entry from stacks. –Critical conditions Empty Full Overflow Stack 1 Stack 2

19 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 19Prof. Q.Wang Question? n stacks in the same array Initialization Push x onto stack 2 After pushing x onto stack 2

20 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 20Prof. Q.Wang Quiz How to arrange the carriages? 123n 123n 132n-1 321n 312n n ……………… … ……………………………… Demo

21 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 21Prof. Q.Wang 5-1.3 Application 1: Bracket Matching Requirement –Develop a program to check that brackets are correctly matched in an input text file. –The brackets are limited in {, }, (, ), [, and ]. Methods –Read a single line of characters and ignore all input other than bracket characters. –Our program need only loop over the input characters, until either a bracketing error is detected or the input file ends.

22 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 22Prof. Q.Wang Algorithm: Read the file character by character. Each opening bracket (, [, or { that is encountered is considered as unmatched and is stored until a matching bracket can be found. Any closing bracket ), ], or } must correspond, in bracket style, to the last unmatched opening bracket, which should now be retrieved and removed from storage. Finally, at the end of the program, we must check that no unmatched opening brackets are left over.

23 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 23Prof. Q.Wang Bracket Matching Program int main() { Stack openings; char symbol; bool is_matched = true; while (is_matched && (symbol = cin.get()) != '\n') { if (symbol == '{' || symbol == '(' || symbol == '[') openings.push(symbol); if (symbol == '}' || symbol == ')' || symbol == ']') { if (openings.empty()) { cout << "Unmatched closing bracket " << symbol << " detected." << endl; is_matched = false; }

24 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 24Prof. Q.Wang else { char match; openings.top(match); openings.pop(); is_matched = (symbol == '}' && match == '{') || (symbol == ')' && match == '(') || (symbol == ']' && match == '['); if (!is_matched) cout << "Bad match " << match << symbol << endl; } if (!openings.empty()) cout << "Unmatched opening bracket(s) detected." << endl; }

25 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 25Prof. Q.Wang 4-2.4 Application 2: Reverse Polish calculator Expression –Infix: a+b*(c-d)-e/f –Postfix (Reverse Polish Notation): abcd-*+ef/- –Prefix (Polish Notation): -+a*b-cd/ef Operands: a, b, c, d, e, f Operators: +, -, *, /, Delimiter: (, )

26 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 26Prof. Q.Wang Expression Evaluation How to calculate the value of the expression? a+b*(c-d)-e/f abcd-*+ef/--+a*b-cd/ef Prefix expression Postfix expression Infix expression

27 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 27Prof. Q.Wang // The program has executed simple arithmetic commands entered by the // user. // Uses: The class Stack and the functions introduction, instructions, // do_command, and get_command. typedef double Stack_entry; int main() { Stack stored_numbers; introduction(); instructions(); while (do_command(get_command(), stored_numbers)); } Reverse Polish calculator Demo

28 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 28Prof. Q.Wang Obtaining command The auxiliary function get_command obtains a command from the user, checking that it is valid and converting it to lower case by using the string function tolower() that is declared in the standard header file cctype.

29 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 29Prof. Q.Wang char get_command() { char command; bool waiting = true; cout :"; while (waiting) { cin >> command; command = tolower(command); if (command == '?' || command == '=' || command == '+' || command == '-' || command == '*' || command == '/' || command == 'q' ) waiting = false; else { cout << "Please enter a valid command:" << endl << "[?]push to stack [=]print top" << endl << "[+] [-] [*] [/] are arithmetic operations" << endl << "[Q]uit." << endl; } return command; }

30 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 30Prof. Q.Wang bool do_command(char command, Stack &numbers) // Pre: The first parameter specifies a valid calculator command. // Post: The command specified by the first parameter has been applied // to the Stack of numbers given by the second parameter. // A result of true is returned unless command == 'q'. // Uses: The class Stack. { double p, q; switch (command) { case '?': cout << "Enter a real number: " << flush; cin >> p; if (numbers.push(p) == overflow) cout << "Warning: Stack full, lost number" << endl; break;

31 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 31Prof. Q.Wang case '+': if (numbers.top(q) == underflow) cout << "Stack empty" << endl; else { numbers.pop(); if (numbers.top(p) == underflow) { cout << "Stack has just one entry" << endl; numbers.push(q); } else { numbers.pop(); if (numbers.push( p+q ) == overflow) cout << "Warning: Stack full, lost result" << endl; } break;

32 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 32Prof. Q.Wang case '-': if (numbers.top(q) == underflow) cout << "Stack empty" << endl; else { numbers.pop(); if (numbers.top(p) == underflow) { cout << "Stack has just one entry" << endl; numbers.push(q); } else { numbers.pop(); if (numbers.push( p-q ) == overflow) cout << "Warning: Stack full, lost result" << endl; } break;

33 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 33Prof. Q.Wang case ‘*': if (numbers.top(q) == underflow) cout << "Stack empty" << endl; else { numbers.pop(); if (numbers.top(p) == underflow) { cout << "Stack has just one entry" << endl; numbers.push(q); } else { numbers.pop(); if (numbers.push( p*q ) == overflow) cout << "Warning: Stack full, lost result" << endl; } break;

34 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 34Prof. Q.Wang case ‘/': if (numbers.top(q) == underflow) cout << "Stack empty" << endl; else { numbers.pop(); if (numbers.top(p) == underflow) { cout << "Stack has just one entry" << endl; numbers.push(q); } else { numbers.pop(); if (numbers.push( p/q ) == overflow) cout << "Warning: Stack full, lost result" << endl; } break;

35 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 35Prof. Q.Wang case 'q': cout << "Calculation finished.\n"; return false; } return true; }

36 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 36Prof. Q.Wang 5-1.5 Application 3: Infix Expression to Postfix Expression –Infix: a+b*(c-d)-e/f –Postfix (Reverse Polish Notation): abcd-*+ef/- Components –Operands: a, b, c, d, e, f –Operators: +, -, *, /, –Delimiter: (, ), #

37 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 37Prof. Q.Wang #a+b*(c-d)-e/f# abcd-*+ef/- A specific stack OPTR is used to store temporary operators, such as +, *, and ( in above expression. isp (in stack priority): the priority of operator at the top of OPTR stack. icp (incoming priority): the new incoming operator priority. If isp < icp, push the incoming operator into OPTR If isp > icp, output and pop the top of OPTR If isp = icp, scan next item and pop the top of OPTR

38 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 38Prof. Q.Wang Priority of operators +-*/()# +>><<<>> ->><<<>> *>>>><>> />>>><>> (<<<<<= )>>>>>> #<<<<<= -- isp -- icp

39 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 39Prof. Q.Wang Infix expression: a+b*(c-d)-e/f StepItemsTypeActivityOptr StackOutput 0# 1aoperanda 2+operatorisp(#) < icp(+)#+a 3boperand#+ab 4*operatorisp(+) < icp(*)#+*ab 5(operatorisp(*) < icp(()#+*(ab 6coperand#+*(abc 7-operatorisp(() < icp(-)#+*(-abc 8doperand#+*(-abcd 9)operatorisp(-) > icp())#+*(abcd- ==#+*abcd-

40 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 40Prof. Q.Wang #a+b*(c-d)-e/f# abcd-*+ef/- 10-operatorisp(*) > icp(-)#+abcd-* isp(+) > icp(-)#abcd-*+ isp(#) < icp(-)#-abcd-*+ 11eoperand#-abcd-*+e 12/Operatorisp(-) < icp(/)#-/abcd-*+e 13fOperand#-/abcd-*+ef 14#Operatorisp(/) > icp(#)#-abcd-*+ef/ isp(-) > icp(#)#abcd-*+ef/- ==, end

41 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 41Prof. Q.Wang void postfix (expression e) { Stack OPTR; char ch, y; OPTR.clear(); OPTR.push(‘#’); while (cin.get(ch)){ if (isdigit(ch)) cout <<ch; else { OPTR.top(y); switch(y, ch) { case <: OPTR.push(ch); break; case >: cout << y; OPTR.pop(); break; case =: OPTR.pop(); }

42 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 42Prof. Q.Wang Summary The characteristic of Stack ADT of Stack –Sequential form for Stacks Implementation of Stack –push() –pop() –top() Application of Stacks –Expression evaluation

43 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 43Prof. Q.Wang Chapter 5-2 Queues Table of Contents –QueuesQueues –ADT Queues and Linear ImplementationADT Queues and Linear Implementation –Circular Implementations of QueuesCircular Implementations of Queues –Linked Queue ImplementationLinked Queue Implementation –Demonstration and TestingDemonstration and Testing Application 1: Fibonacci Array Application 2: Yangvi Triangle Application 3: Airport Simulation –SummarySummary

44 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 44Prof. Q.Wang 5-2.1 Queues Definition –A queue is a special linear list. –A queue is a list in which all addition to the list are made at one end, and all deletions from the list are made at the other end. –FIFO structure: The first entry which is added is the first one that will be removed. (First in first out)

45 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 45Prof. Q.Wang Example –A queue is a waiting line, like a people waiting to purchase tickets, where the first person in line is the first person served.

46 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 46Prof. Q.Wang Concepts front –The specific end of linear list at which elements can removed. –The entry in a queue ready to be served, that is, the first entry that will be removed from the queue, is called the front (head) entry of the queue. rear –The specific end of linear list at which elements can added or inserted. –The one most recently added, is called the rear (tail) entry of the queue.

47 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 47Prof. Q.Wang Examples of Addition and Deletion Empty Queue Alternative methods –insert, append, enqueue –delete, serve, dequeue

48 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 48Prof. Q.Wang 5-2.2 ADT of Queues template class Queue { public: Queue ( int=10 ); void EnQueue ( const Type & item); Type DeQueue ( ); Type GetFront ( ); void MakeEmpty ( ); int IsEmpty ( ) const ; int IsFull ( ) const; }

49 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 49Prof. Q.Wang Problem of linear implementation in array For example rear=5, front=1 the actual length of queue is 4 however, no new entry could be appended into queue. Why?

50 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 50Prof. Q.Wang Problem of linear implementation in array Problem –front and rear indices will move to the high end of the array after several Enqueue and Dequeue operations Solution –keep the front index always in the first location of the array — long time taken –thinking of the array as a circle rather than a straight line

51 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 51Prof. Q.Wang

52 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 52Prof. Q.Wang 5-2.3 Circular Implementations of Queues Class declaration #include template class Queue { public: Queue ( int=10 ); ~Queue ( ) { delete [ ] elements; } void EnQueue ( const Type & item); Type DeQueue ( ); Type GetFront ( ); void MakeEmpty ( ) { front = rear = 0; }

53 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 53Prof. Q.Wang int IsEmpty ( ) const { return front == rear; } int IsFull ( ) const { return (rear+1) % maxSize == front; } int Length ( ) const { return (rear - front+maxSize) % maxSize;} private: int rear, front; Type *elements; int maxSize; }

54 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 54Prof. Q.Wang

55 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 55Prof. Q.Wang Circular array in C++ Equivalent methods to increment an index i in a circular array: –i = ((i+1) == max) ? 0 : (i+1); –if ((i+1) == max) i=0 ; else i=i+1; –i = (i+1) % max;

56 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 56Prof. Q.Wang Boundary conditions Empty –front == rear; –due to front++

57 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 57Prof. Q.Wang Boundary conditions Full –rear == front –due to rear++

58 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 58Prof. Q.Wang Empty queueEnqueue Dequeue Full queue

59 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 59Prof. Q.Wang Solutions for boundary conditions Insist on leaving one empty position in the array so that the queue is considered as full when the rear index has moved Introduce a new bool variable to indicate the statuses of the queue, empty or full Set one or both of indices to some value(s) that would otherwise never occur in order to indicate an empty (or full) queue

60 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 60Prof. Q.Wang Implementations of Methods template Queue :: Queue ( int sz ) : front (0), rear (0), maxSize (sz) { elements = new Type[maxSize]; assert ( elements != 0 ); } template void Queue :: EnQueue ( const Type & item ) { assert ( !IsFull ( ) ); rear = (rear+1) % MaxSize; elements[rear] = item; }

61 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 61Prof. Q.Wang template Type Queue :: DeQueue ( ) { assert ( !IsEmpty ( ) ); front = ( front+1) % MaxSize; return elements[front]; } template Type Queue :: GetFront ( ) { assert ( !IsEmpty ( ) ); return elements[front]; }

62 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 62Prof. Q.Wang 5-2.4 Linked Queue template class Queue; template class QueueNode { friend class Queue ; private: Type data; //Data element QueueNode *link; //pointer to next item QueueNode ( Type d=0, QueueNode *l=NULL ) : data (d), link (l) { } };

63 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 63Prof. Q.Wang template class Queue { public: Queue ( ) : rear ( NULL ), front ( NULL ) { } ~Queue ( ); void EnQueue ( const Type & item ); Type DeQueue ( ); Type GetFront ( ); void MakeEmpty ( ); //same as function ~Queue( ) int IsEmpty ( ) const { return front == NULL; } private: QueueNode *front, *rear; //Pointer indicators };

64 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 64Prof. Q.Wang Member functions template Queue :: ~Queue ( ) { //Destructor QueueNode *p; while ( front != NULL ) { //Release every node step by step p = front; front = front→link; delete p; }

65 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 65Prof. Q.Wang template void Queue :: EnQueue ( const Type & item ) { //append a new item into Queue if ( front == NULL ) //NULL Queue front = rear = new QueueNode ( item, NULL ); else //Not NULL rear = rear→link = new QueueNode ( item, NULL ); }

66 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 66Prof. Q.Wang template Type Queue :: DeQueue ( ) { //Return the front item and then remove it from Queue assert ( !IsEmpty ( ) ); QueueNode *p = front; Type retvalue = p→data; front = front→link; delete p; return retvalue; } template Type Queue :: GetFront ( ) { assert ( !IsEmpty ( ) ); return front→data; }

67 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 67Prof. Q.Wang 5-2.5 Demonstration and Testing Objective –Test the performance of the implementations for queues Method –Menu driven program –get_command() from control board –do_command according to the command and demonstrate the functions of class Queue

68 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 68Prof. Q.Wang int main() /* Post: Accepts commands from user as a menu-driven demonstration program for the class Queue. Uses: The class Queue and the functions introduction, get_command, and do_command. */ { Queue test_queue; introduction(); while (do_command(get_command(), test_queue)); }

69 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 69Prof. Q.Wang void help() // Post: A help screen for the program is printed, giving the meaning // of each command that the user may enter. { cout << endl << "This program allows the user to enter one command" << endl << "(but only one) on each input line." << endl << "For example, if the command S is entered, then" << endl << "the program will serve the front of the queue." << endl << endl << " The valid commands are:" << endl << "A - Append the next input character to the queue" << endl;

70 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 70Prof. Q.Wang cout<< " S - Serve the front of the queue" << endl << " R - Retrieve and print the front entry." << endl << " # - The current size of the queue" << endl << " C - Clear the queue (same as delete)" << endl << " P - Print the queue" << endl << " H - This help screen" << endl << " Q - Quit" << endl to continue." << flush; char c; do { cin.get(c); } while (c != '\n'); }

71 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 71Prof. Q.Wang bool do_command(char c, Queue &test_queue) // Pre: c represents a valid command. // Post: Performs the given command c on the // Extended_queue test_queue. Returns false if c == 'q', // otherwise returns true. // Uses: The class Extended_queue. { bool continue_input = true; Queue_entry x; switch (c) {

72 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 72Prof. Q.Wang case 'r': if (test_queue.retrieve(x) == underflow) cout << "Queue is empty." << endl; else cout << endl << "The first entry is: " << x << endl; break; case 'q': cout << “Queue demonstration finished." << endl; continue_input = false; break; // Additional cases will cover other commands. } return continue_input; }

73 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 73Prof. Q.Wang 5-2.6 Application 1: Fibonacci Array 112358132134………… F n =F n-1 +F n-2, F 1 =1, F 2 =1 11 Front 11 2 Rear

74 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 74Prof. Q.Wang 11 Front 23 Rear 11 Front 235 Rear 11 Front 2358 Rear 11 Front 235813 Rear

75 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 75Prof. Q.Wang #include "queue.h" void Fibonacci ( int n ) { Queue q; createQueue ( &q); enQueue (&q, 1); enQueue (&q, 1); int s,t; getHead (&q, &s); deQueue (&q); printf (“%d ”, s ); for ( int i=2; i<=n; i++ ) { getHead (&q, &t); deQueue (&q); enQueue (&q, s+t ); s = t; printf (“%d ”, s ); } printf (“\n”); }

76 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 76Prof. Q.Wang Pascal’s triangle 5-2.7 Application 2: Yangvi Triangle

77 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 77Prof. Q.Wang Relation between i-th row and (i+1)-th elements

78 Prof. Q.Wang Q. Wang 78 0 1 1 0 0 1 2 1 0 0 1 3 3 1 0 0 1 4 6 4 1 0 0 1 5 10 10 5 1 0 0 1 6 15 20 15 6 1 0 0 1 7 21 35 35 21 7 1 0 Principle

79 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 79Prof. Q.Wang Principle

80 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 80Prof. Q.Wang #include "queue.h" void YANGVI ( int n ) { Queue q; q.clear ( ); q.append (1); q.append (1); int s = 0; for ( int i=1; i<=n; i++ ) { cout << endl; q.append (0); for ( int j=1; j<=i+2; j++ ) { int t; q.serve_and_retrieve (&t); q.append (s+t ); s = t; if ( j != i+2 ) cout << s << ' '; }

81 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 81Prof. Q.Wang 5-2.8 Application 3: Simulation of an Airport Simulation –Simulation is the use of one system to imitate the behavior of another system –A computer simulation is a program to imitate the behavior of the system under study

82 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 82Prof. Q.Wang Airport simulation

83 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 83Prof. Q.Wang Airport simulation Requirement –The same runway is used for both landings and takeoffs. –One plane can land or takeoff in a unit of time, but not both. –A random number of planes arrive in each time unit. –A plane waiting to land goes before one waiting to takeoff. –The planes that are waiting are kept in queues landing and takeoff, both of which have a strictly limited size.

84 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 84Prof. Q.Wang Specification of simulation Runway class –Members Landing queue, takeoff queue and other variables –Runway status idle, land, takeoff Plane_status class –Plane status null, arriving, departing Initialization –specifies the number of time units in the simulation, the maximal queue sizes permitted, and the expected arrival and departure rates for the airport.

85 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 85Prof. Q.Wang enum Runway_activity {idle, land, takeoff}; class Runway { public: Runway(int limit); Error_code can_land(const Plane &current); Error_code can_depart(const Plane &current); Runway_activity activity(int time, Plane &moving); void shut_down(int time) const; private: Queue landing; // landing queue Queue takeoff; // takeoff queue int queue_limit; The Runway Class Specification

86 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 86Prof. Q.Wang // number of planes asking to land int num_land_requests; // number of planes asking to take off int num_takeoff_requests; // number of planes that have landed int num_landings; // number of planes that have taken off int num_takeoffs; // number of planes queued to land int num_land_accepted; // number of planes queued to take off int num_takeoff_accepted;

87 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 87Prof. Q.Wang // number of landing planes refused int num_land_refused; // number of departing planes refused int num_takeoff_refused; // total time of planes waiting to land int land_wait; // total time of planes waiting to take off int takeoff_wait; // total time runway is idle int idle_time; };

88 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 88Prof. Q.Wang enum Plane_status {null, arriving, departing}; class Plane { public: Plane(); Plane(int flt, int time, Plane_status status); void refuse() const; void land(int time) const; void fly(int time) const; int started() const; private: int flt_num; int clock_start; Plane_status state; }; The Plane Class Specification

89 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 89Prof. Q.Wang void initialize(int &end_time, int &queue_limit, double &arrival_rate, double &departure_rate) /* Pre: The user specifies the number of time units in the simulation, the maximal queue sizes permitted, and the expected arrival and departure rates for the airport. Post: The program prints instructions and initializes the parameters end_time, queue_limit, arrival_rate, and departure_rate to the specified values. Uses: utility function user_says_yes */ Initialization

90 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 90Prof. Q.Wang void initialize(int &end_time, int &queue_limit, double &arrival_rate, double &departure_rate) { cout << "This program simulates an airport with only one runway." << endl << "One plane can land or depart in each unit of time." << endl; cout << "Up to what number of planes can be waiting to land or take off at any time? " << flush; cin >> queue_limit; cout << "How many units of time will the simulation run?" << flush; cin >> end_time; bool acceptable;

91 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 91Prof. Q.Wang do { cout << "Expected number of arrivals per unit time?" << flush; cin >> arrival_rate; cout << "Expected number of departures per unit time?" << flush; cin >> departure_rate; if (arrival_rate < 0.0 || departure_rate < 0.0) cerr << "These rates must be nonnegative." << endl; else acceptable = true; if (acceptable && arrival_rate + departure_rate > 1.0) cerr << "Safety Warning: This airport will become saturated. " << endl; } while (!acceptable); }

92 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 92Prof. Q.Wang // Runway Initialization Runway::Runway(int limit) // Post: The Runway data members are initialized to record no prior // Runway use and to record the limit on queue sizes. { queue_limit = limit; num_land_requests = num_takeoff_requests = 0; num_landings = num_takeoffs = 0; num_land_refused = num_takeoff_refused = 0; num_land_accepted = num_takeoff_accepted = 0; land_wait = takeoff_wait = idle_time = 0; } Runway methods

93 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 93Prof. Q.Wang // Accepting a New Plane into the landing queue Error_code Runway::can_land(const Plane &current) // Post: If possible, the Plane current is added to the landing Queue; // otherwise, an Error_code of overflow is returned. The Runway statistics // are updated. // Uses: class Queue. { Error_code result; if (landing.size() < queue_limit) result = landing.append(current); else result = fail; num_land_requests++; if (result != success) num_land_refused++; else num_land_accepted++; return result; }

94 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 94Prof. Q.Wang // Accepting a New Plane into the takeoff queue Error_code Runway::can_depart(const Plane &current) // Post: If possible, the Plane current is added to the takeoff Queue; // otherwise, an Error_code of overflow is returned. The Runway statistics // are updated. // Uses: class Queue. { Error_code result; if (takeoff.size() < queue_limit) result = takeoff.append(current); else result = fail; num_takeoff_requests++; if (result != success) num_takeoff_refused++; else num_takeoff_accepted++; return result; }

95 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 95Prof. Q.Wang Runway_activity Runway::activity(int time, Plane &moving) // Post: If the landing Queue has entries, its front Plane is copied to the // parameter moving and a result land is returned. Otherwise, if the // takeoff Queue has entries, its front Plane is copied to the parameter // moving and a result takeoff is returned. Otherwise, idle is returned. // Runway statistics are updated. // Uses: class Queue. { Runway_activity in_progress; if (!landing.empty()) { landing.retrieve(moving); land_wait += time - moving.started(); num_landings++; in_progress = land; Handling Runway Access

96 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 96Prof. Q.Wang landing.serve(); } else if (!takeoff.empty()) { takeoff.retrieve(moving); takeoff_wait += time - moving.started(); num_takeoffs++; in_progress = takeoff; takeoff.serve(); } else { idle_time++; in_progress = idle; } return in_progress; }

97 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 97Prof. Q.Wang Plane::Plane(int flt, int time, Plane_status status) // Post: The Plane data members flt_num, clock_start, and state are set to // the values of the parameters flt, time and status, respectively. { flt_num = flt; clock_start = time; state = status; cout << "Plane number " << flt << " ready to "; if (status == arriving) cout << "land." << endl; else cout << "take off." << endl; } Plane Initialization

98 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 98Prof. Q.Wang Plane::Plane() // Post: The Plane data members flt_num, clock_start, state are set to // illegal default values. { flt_num = -1; clock_start = -1; state = null; } Plane Initialization

99 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 99Prof. Q.Wang // Refusing a plane void Plane::refuse() const // Post: Processes a Plane wanting to use Runway, when the Queue is // full. { cout << "Plane number " << flt_num; if (state == arriving) cout << " directed to another airport" << endl; else cout << " told to try to takeoff again later" << endl; } Plane Methods

100 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 100Prof. Q.Wang // Processing an arriving plane void Plane::land(int time) const // Post: Processes a Plane that is landing at the specified time. { int wait = time - clock_start; cout << time << ": Plane number " << flt_num << " landed after " << wait << " time unit" << ((wait == 1) ? "" : "s") << " in the takeoff queue." << endl; }

101 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 101Prof. Q.Wang // Processing a departing plane void Plane::fly(int time) const // Post: Process a Plane that is taking off at the specified time. { int wait = time - clock_start; cout << time << ": Plane number " << flt_num << " took off after " << wait << " time unit" << ((wait == 1) ? "" : "s") << " in the takeoff queue." << endl; }

102 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 102Prof. Q.Wang // Communicating a plane;s arrival data int Plane::started() const // Post: Return the time that the Plane entered the airport system. { return clock_start; } // Marking an idle time unit void run_idle(int time) // Post: The specified time is printed with a message that the runway is // idle. { cout << time << ": Runway is idle." << endl; }

103 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 103Prof. Q.Wang void Runway::shut_down(int time) const // Post: Runway usage statistics are summarized and printed. { cout << "Simulation has concluded after " << time << " time units." << endl << "Total number of planes processed " << (num_land_requests + num_takeoff_requests) << endl << "Total number of planes asking to land " << num_land_requests << endl << "Total number of planes asking to take off " << num_takeoff_requests << endl << "Total number of planes accepted for landing " << num_land_accepted << endl Finish the simulation

104 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 104Prof. Q.Wang << "Total number of planes accepted for takeoff " << num_takeoff_accepted << endl << "Total number of planes refused for landing " << num_land_refused << endl << "Total number of planes refused for takeoff " << num_takeoff_refused << endl << "Total number of planes that landed " << num_landings << endl << "Total number of planes that took off " << num_takeoffs << endl << "Total number of planes left in landing queue " << landing.size() << endl << "Total number of planes left in takeoff queue " << takeoff.size() << endl;

105 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 105Prof. Q.Wang cout << "Percentage of time runway idle " << 100.0 * (( float ) idle_time) / (( float ) time) << "%" << endl; cout << "Average wait in landing queue " << (( float ) land_wait) / (( float ) num_landings) << " time units" << endl; cout << "Average wait in takeoff queue " << (( float ) takeoff_wait) / (( float ) num_takeoffs) << " time units" << endl; cout << "Average observed rate of planes wanting to land " << (( float ) num_land_requests) / (( float ) time) << " per time unit" << endl; cout << "Average observed rate of planes wanting to take off " << (( float ) num_takeoff_requests) / (( float ) time) << " per time unit" << endl; }

106 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 106Prof. Q.Wang int main() // Airport simulation program /* Pre: The user must supply the number of time intervals the simulation is to run, the expected number of planes arriving, the expected number of planes departing per time interval, and the maximum allowed size for runway queues. Post: The program performs a random simulation of the airport, showing the status of the runway at each time interval, and prints out a summary of airport operation at the conclusion. Uses: Classes Runway, Plane, Random and functions run_idle, initialize. */ Main program of simulation

107 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 107Prof. Q.Wang { int end_time; // time to run simulation int queue_limit; // size of Runway queues int flight_number = 0; double arrival_rate, departure_rate; initialize(end_time, queue_limit, arrival_rate, departure_rate); Random variable; Runway small_airport(queue_limit); for (int current_time = 0; current_time < end_time; current_time++) { // loop over time intervals int number_arrivals = variable.poisson(arrival_rate);

108 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 108Prof. Q.Wang // current arrival requests for (int i = 0; i < number_arrivals; i++) { Plane current_plane(flight_number++, current_time, arriving); if (small_airport.can_land(current_plane) != success) current_plane.refuse(); } int number_departures= variable.poisson(departure_rate); //current departure requests for (int j = 0; j < number_departures; j++) { Plane current_plane(flight_number++, current_time, departing); if (small_airport.can_depart(current_plane) != success) current_plane.refuse(); }

109 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 109Prof. Q.Wang Plane moving_plane; switch (small_airport.activity(current_time, moving_plane)) { // Let at most one Plane onto the Runway at current_time. case land: moving_plane.land(current_time); break; case takeoff: moving_plane.fly(current_time); break; case idle: run_idle(current_time); } } // end of loop over time intervals small_airport.shut_down(end_time); }

110 Lecture Notes: Data Structures and Algorithms Software College, Northwestern Polytechnical Univ. 110Prof. Q.Wang Summary Queues and ADT of Queues Contiguous storage for queues Implementations of methods for Queue class Demonstration and testing for Queues Application: Discrete event simulation –Airport and runway –Bank transactions –Ticket selling


Download ppt "Prof. Qing Wang Lecture 5 Stack and Queue Lecture Notes: Data Structures and Algorithms."

Similar presentations


Ads by Google