Stacks and Queues 2 struct Node double data
Stacks and Queues
2 struct Node{ double data; Node* next; }; More complete list ADT class List { public: List(); // constructor List(const List& list); // copy constructor ~List(); // destructor List& operator=(const List& list); // assignment operator bool empty() const; // boolean function void add. Head(double x); // add to the head double delete. Head(); // delete the head and get the head element // List& rest(); // get the rest of the list with the head removed // double head. Element() const; // get the head element void add. End(double x); double delete. End(); // double end. Element(); // add to the end // delete the end and get the end element // get the element at the end bool search. Node(double x); void insert. Node(double x); void delete. Node(double x); // search for a given x // insert x in a sorted list // delete x in a sorted list … void print() const; int length() const; private: Node* head; }; // output // count the number of elements
3 Stack Overview * Stack ADT * Basic operations of stack n Pushing, popping etc. * Implementations of stacks using array n linked list n
4 Stack * A stack is a list in which insertion and deletion take place at the same end This end is called top n The other end is called bottom n * Stacks are known as LIFO (Last In, First Out) lists. n The last element inserted will be the first to be retrieved
5 Push and Pop * Primary operations: Push and Pop * Push n Add an element to the top of the stack * Pop n Remove the element at the top of the stack empty stack push an element top top A push another B A pop top A
6 Implementation of Stacks * Any list implementation could be used to implement a stack Arrays (static: the size of stack is given initially) n Linked lists (dynamic: never become full) n * We will explore implementations based on array and linked list
7 Stack ADT class Stack { public: Stack(); // constructor Stack(const Stack& stack); // copy constructor ~Stack(); // destructor bool empty() const; void push(const double x); double pop(); // change the stack double top() const; // bool full(); // void print() const; ‘physical’ constructor/destructor update, ‘logical’ constructor/destructor, composition/decomposition // keep the stack unchanged inspection, access // optional private: … }; Compare with List, see that it’s ‘operations’ that define the type!
8 Using Stack int main(void) { Stack stack; stack. push(5. 0); stack. push(6. 5); stack. push(-3. 0); stack. push(-8. 0); stack. print(); cout << "Top: " << stack. top() << endl; stack. pop(); cout << "Top: " << stack. top() << endl; while (!stack. empty()) stack. pop(); stack. print(); return 0; } result
9 Stack using linked lists struct Node{ public: double data; Node* next; }; class Stack { public: Stack(); // constructor Stack(const Stack& stack); // copy constructor ~Stack(); // destructor bool empty() const; void push(const double x); double pop(); // change the stack bool full(); // unnecessary for linked lists double top() const; // keep the stack unchanged void print() const; private: Node* top; };
10 Push (add. Head), Pop (delete. Head) void List: : add. Head(int newdata){ Nodeptr new. Ptr = new Node; new. Ptr->data = newdata; new. Ptr->next = head; From ‘add. Head’ to ‘push’ head = new. Ptr; } void Stack: : push(double x){ Node* new. Ptr = new Node; new. Ptr->data = x; new. Ptr->next = top; top = new. Ptr; }
11 Implementation based on ‘existing’ linked lists * Optional to learn * Good to see that we may ‘re-use’ linked lists
12 * * Now let’s implement a stack based on a linked list To make the best out of the code of List, we implement Stack by inheriting List n To let Stack access private member head, we make Stack as a friend of List class List { public: List() { head = NULL; } ~List(); // constructor // destructor bool empty() { return head == NULL; } Node* insert. Node(int index, double x); int delete. Node(double x); int search. Node(double x); void print. List(void); private: Node* head; friend class Stack; };
13 class Stack : public List { from List public: Stack() {} ~Stack() {} double top() { if (head == NULL) { cout << "Error: the stack is empty. " << endl; return -1; } else return head->data; } void push(const double x) { Insert. Node(0, x); } double pop() { if (head == NULL) { cout << "Error: the stack is empty. " << endl; return -1; } else { double val = head->data; Delete. Node(val); Note: the stack return val; } implementation } void print. Stack() { print. List(); } }; based on a linked list will never be full.
14 Stack using arrays class Stack { public: Stack(int size = 10); ~Stack() { delete [] values; } // constructor // destructor bool empty() { return top == -1; } void push(const double x); double pop(); bool full() { return top == max. Top; } double top(); void print(); private: int max. Top; // max stack size = size - 1 int top; // current top of stack double* values; // element array };
15 * Attributes of Stack max. Top: the max size of stack n top: the index of the top element of stack n values: point to an array which stores elements of stack n * Operations of Stack n n n empty: return true if stack is empty, return false otherwise full: return true if stack is full, return false otherwise top: return the element at the top of stack push: add an element to the top of stack pop: delete the element at the top of stack print: print all the data in the stack
16 Stack constructor Allocate a stack array of size. By default, size = 10. n Initially top is set to -1. It means the stack is empty. n When the stack is full, top will have its maximum value, i. e. n size – 1. Stack: : Stack(int size /*= 10*/) { values = new double[size]; top = -1; max. Top = size - 1; } Although the constructor dynamically allocates the stack array, the stack is still static. The size is fixed after the initialization.
17 * void push(const double x); Push an element onto the stack n Note top always represents the index of the top element. After pushing an element, increment top. n void Stack: : push(const double x) { if (full()) // if stack is full, print error cout << "Error: the stack is full. " << endl; else values[++top] = x; }
18 * double pop() Pop and return the element at the top of the stack n Don’t forgot to decrement top n double Stack: : pop() { if (empty()) { //if stack is empty, print error cout << "Error: the stack is empty. " << endl; return -1; } else { return values[top--]; } }
19 * double top() Return the top element of the stack n Unlike pop, this function does not remove the top element n double Stack: : top() { if (empty()) { cout << "Error: the stack is empty. " << endl; return -1; } else return values[top]; }
20 * void n print() Print all the elements void Stack: : print() { cout << "top -->"; for (int i = top; i >= 0; i--) cout << "t|t" << values[i] << "t|" << endl; cout << "t|--------|" << endl; }
21 Stack Application: Balancing Symbols * To check that every right brace, bracket, and parentheses must correspond to its left counterpart n e. g. [( )] is legal, but [( ] ) is illegal * Algorithm (1) Make an empty stack. (2) Read characters until end of file i. If the character is an opening symbol, push it onto the stack ii. If it is a closing symbol, then if the stack is empty, report an error iii. Otherwise, pop the stack. If the symbol popped is not the corresponding opening symbol, then report an error (3) At end of file, if the stack is not empty, report an error
22 Stack Application: function calls and recursion * Take the example of factorial! And run it. #include <iostream> using namespace std; int fac(int n){ int product; if(n <= 1) product = 1; else product = n * fac(n-1); return product; } void main(){ int number; cout << "Enter a positive integer : " << endl; ; cin >> number; cout << fac(number) << endl; }
23 Tracing the program … Assume the number typed is 3. fac(3): 3<=1 ? No. product 3 = 3*fac(2): 2<=1 ? No. product 2 = 2*fac(1): 1<=1 ? Yes. return 1 has the final returned value 6 product 3=3*2=6, return 6, product 2=2*1=2, return 2,
24 Call is to ‘push’ and return is to ‘pop’! top fac(1) prod 1=1 fac(2) prod 2=2*fac(1) fac(3) prod 3=3*fac(2)
25 Array versus linked list implementations * push, pop, top are all constant-time operations in both array and linked list implementation n For array implementation, the operations are performed in very fast constant time
26 Queue Overview * Queue ADT * Basic operations of queue n Enqueuing, dequeuing etc. * Implementation of queue Linked list n Array n
27 Queue * A queue is also a list. However, insertion is done at one end, while deletion is performed at the other end. * It is “First In, First Out (FIFO)” order. n Like customers standing in a check-out line in a store, the first customer in is the first customer served.
28 Enqueue and Dequeue * Primary queue operations: Enqueue and Dequeue * Like check-out lines in a store, a queue has a front and a rear. * Enqueue – insert an element at the rear of the queue * Dequeue – remove an element from the front of the queue Remove (Dequeue) front rear Insert (Enqueue)
29 Implementation of Queue * Just as stacks can be implemented as arrays or linked lists, so with queues. * Dynamic queues have the same advantages over static queues as dynamic stacks have over static stacks
30 Queue ADT class Queue { public: Queue(); Queue(Queue& queue); ~Queue(); bool empty(); void enqueue(double x); double dequeue(); void print(void); // bool full(); // optional private: … }; ‘physical’ constructor/destructor ‘logical’ constructor/destructor
31 Using Queue int main(void) { Queue queue; cout << "Enqueue 5 items. " << endl; for (int x = 0; x < 5; x++) queue. enqueue(x); cout << "Now attempting to enqueue again. . . " << endl; queue. enqueue(5); queue. print(); double value; value=queue. dequeue(); cout << "Retrieved element = " << value << endl; queue. print(); queue. enqueue(7); queue. print(); return 0; }
32 Queue using linked lists Struct Node { double data; Node* next; } class Queue { public: Queue(); Queue(Queue& queue); ~Queue(); bool empty(); void enqueue(double x); double dequeue(); // bool full(); // optional void print(void); private: Node* front; Node* rear; int counter; }; // pointer to front node // pointer to last node // number of elements
33 Implementation of some online member functions … class Queue { public: Queue() { // constructor front = rear = NULL; counter = 0; } ~Queue() { // destructor double value; while (!empty()) dequeue(value); } bool empty() { if (counter) return false; else return true; } void enqueue(double x); double dequeue(); // bool full() {return false; }; void print(void); private: Node* front; Node* rear; int counter; }; // pointer to front node // pointer to last node // number of elements, not compulsary
34 Enqueue (add. End) void Queue: : enqueue(double x) { Node* new. Node = new Node; new. Node->data = x; new. Node->next = NULL; if (empty()) { front = new. Node; } else { rear->next = new. Node; } rear 5 8 rear = new. Node; counter++; } 8 5 new. Node
35 Dequeue (delete. Head) double Queue: : dequeue() { double x; if (empty()) { cout << "Error: the queue is empty. " << endl; exit(1); // return false; } else { x = front->data; Node* next. Node = front->next; delete front; front = next. Node; front counter--; } 3 8 5 return x; } front 8 5
36 Printing all the elements void Queue: : print() { cout << "front -->"; Node* curr. Node = front; for (int i = 0; i < counter; i++) { if (i == 0) cout << "t"; else cout << "tt"; cout << curr. Node->data; if (i != counter - 1) cout << endl; else cout << "t<-- rear" << endl; curr. Node = curr. Node->next; } }
37 Queue using Arrays * There are several different algorithms to implement Enqueue and Dequeue * Naïve way n When enqueuing, the front index is always fixed and the rear index moves forward in the array. rear 3 3 front Enqueue(3) rear 6 Enqueue(6) 3 6 9 front Enqueue(9)
38 * Naïve way (cont’d) n 6 When dequeuing, the front index is fixed, and the element at the front the queue is removed. Move all the elements after it by one position. (Inefficient!!!) rear 9 9 front Dequeue() rear = -1 front Dequeue()
39 * A better way When enqueued, the rear index moves forward. n When dequeued, the front index also moves forward by one element n (front) XXXXOOOOO (rear) OXXXXOOOO (after 1 dequeue, and 1 enqueue) OOXXXXXOO (after another dequeue, and 2 enqueues) OOOOXXXXX (after 2 more dequeues, and 2 enqueues) The problem here is that the rear index cannot move beyond the last element in the array.
40 Using Circular Arrays * Using a circular array * When an element moves past the end of a circular array, it wraps around to the beginning, e. g. n OOOOO 7963 4 OOOO 7963 (after Enqueue(4)) * How to detect an empty or full queue, using a circular array algorithm? n Use a counter of the number of elements in the queue.
41 class Queue { public: Queue(int size = 10); // constructor Queue(Queue& queue); // not necessary! ~Queue() { delete [] values; } // destructor bool empty(void); void enqueue(double x); // or bool enqueue(); double dequeue(); bool full(); void print(void); full() is not essential, can be embedded private: int front; int rear; int counter; int max. Size; double* values; }; // front index // rear index // number of elements // size of array queue // element array
42 * Attributes of Queue front/rear: front/rear index n counter: number of elements in the queue n max. Size: capacity of the queue n values: point to an array which stores elements of the queue n * Operations of Queue n n n empty: return true if queue is empty, return false otherwise full: return true if queue is full, return false otherwise enqueue: add an element to the rear of queue dequeue: delete the element at the front of queue print: print all the data
43 Queue constructor * Queue(int size = 10) Allocate a queue array of size. By default, size = 10. n front is set to 0, pointing to the first element of the array n rear is set to -1. The queue is empty initially. n Queue: : Queue(int size /* = 10 */) { values = new double[size]; max. Size = size; front = 0; rear = -1; counter = 0; }
44 Empty & Full * Since we keep track of the number of elements that are actually in the queue: counter, it is easy to check if the queue is empty or full. bool Queue: : empty() { if (counter==0) return else return } bool Queue: : full() { if (counter < max. Size) else } true; false; return true;
45 Enqueue Or ‘bool’ if you want void Queue: : enqueue(double x) { if (full()) { cout << "Error: the queue is full. " << endl; exit(1); // return false; } else { // calculate the new rear position (circular) rear = (rear + 1) % max. Size; // insert new item values[rear] = x; // update counter++; // return true; } }
46 Dequeue double Queue: : dequeue() { double x; if (empty()) { cout << "Error: the queue is empty. " << endl; exit(1); // return false; } else { // retrieve the front item x = values[front]; // move front = (front + 1) % max. Size; // update counter--; // return true; } return x; }
47 Printing the elements void Queue: : print() { cout << "front -->"; for (int i = 0; i < counter; i++) { if (i == 0) cout << "t"; else cout << "tt"; cout << values[(front + i) % max. Size]; if (i != counter - 1) cout << endl; else cout << "t<-- rear" << endl; } }
48 Using Queue int main(void) { Queue queue; cout << "Enqueue 5 items. " << endl; for (int x = 0; x < 5; x++) queue. enqueue(x); cout << "Now attempting to enqueue again. . . " << endl; queue. enqueue(5); queue. print(); double value; value=queue. dequeue(); cout << "Retrieved element = " << value << endl; queue. print(); queue. enqueue(7); queue. print(); return 0; }
49 Results based on array based on linked list Queue implemented using linked list will be never full!
50 Queue applications * When jobs are sent to a printer, in order of arrival, a queue. * Customers at ticket counters …
- Slides: 50