Stack Queue
Stack Queue
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 addHead(double x); // add to the head double deleteHead(); // delete the head and get the head element // List& rest(); // get the rest of the list with the head removed // double headElement() const; // get the head element
void addEnd(double x); double deleteEnd(); // double endElement(); bool searchNode(double x); void insertNode(double x); void deleteNode(double x); void print() const; int length() const; private: Node* head; };
// add to the end // delete the end and get the end element // get the element at the end // search for a given x // insert x in a sorted list // delete x in a sorted list
Stack Overview
Stack
Implementations
of stacks using
Stack
A stack is a list in which insertion and deletion take place at the same end
Add an element to the top of the stack Remove the element at the top of the stack
push an element top push another pop
Pop
empty stack
top
top
B A
top
Implementation of Stacks
Any
We
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; private: }; physical constructor/destructor
Compare with List, see that its operations that define the type!
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
10
Nodeptr newPtr = new Node; newPtr->data = newdata; newPtr->next = head; From addHead to push head = newPtr;
}
void Stack::push(double x){ Node* newPtr = new Node; newPtr->data = x; newPtr->next = top; top = newPtr;
11
12
Now lets implement a stack based on a linked list To make the best out of the code of List, we implement Stack by inheriting List To let Stack access private member head, we make Stack as a friend of List
// constructor // destructor
bool empty() { return head == NULL; } Node* insertNode(int index, double x); int deleteNode(double x); int searchNode(double x); void printList(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) { InsertNode(0, x); } double pop() { if (head == NULL) { cout << "Error: the stack is empty." << endl; return -1; } else { double val = head->data; DeleteNode(val); Note: the stack return val; } implementation }
14
15
Attributes of Stack
maxTop: the max size of stack top: the index of the top element of stack values: point to an array which stores elements of stack
Operations of Stack
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. Initially top is set to -1. It means the stack is empty. When the stack is full, top will have its maximum value, i.e.
size 1.
Stack::Stack(int size /*= 10*/) { values = new double[size]; top = -1; maxTop = 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 an element onto the stack Note top always represents the index of the top element. After pushing an element, increment top.
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 Dont forgot to decrement top
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 Unlike pop, this function does not remove the top element
double Stack::top() { if (empty()) { cout << "Error: the stack is empty." << endl; return -1; } else return values[top]; }
20
void
print()
void Stack::print() { cout << "top -->"; for (int i = top; i >= 0; i--) cout << "\t|\t" << values[i] << "\t|" << endl; cout << "\t|---------------|" << endl; }
21
check that every right brace, bracket, and parentheses must correspond to its left counterpart
e.g. [( )] is legal, but [( ] ) is illegal
How?
Need to memorize Use a counter, several counters, each for a type of parenthesis
22
(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
23
Postfix
Convert
infix to postfix
Calculator
24
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; }
25
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; }
26
product2=2*1=2, return 2,
27
28
is relative static variables are from a Stack dynamic variables are from a heap (seen later )
29
pop, top are all constant-time operations in both array and linked list implementation
For array implementation, the operations are performed in very fast constant time
30
Queue Overview
Queue
Implementation
of queue
31
Queue
A
queue is also a list. However, insertion is done at one end, while deletion is performed at the other end.
It
32
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)
33
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
34
Queue ADT
class Queue { public: Queue(); Queue(Queue& queue); ~Queue(); bool empty(); void enqueue(double x); double dequeue();
physical constructor/destructor
logical constructor/destructor
private: };
35
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; }
Using Queue
36
private: Node* front; Node* rear; int counter; }; // pointer to front node // pointer to last node // number of elements
37
38
Enqueue (addEnd)
void Queue::enqueue(double x) {
Node* newNode = new Node; newNode->data = x; newNode->next = NULL; if (empty()) { front = newNode; } else { rear->next = newNode; } rear = newNode; counter++; }
rear
5
rear
5
newNode
39
Dequeue
(deleteHead)
double Queue::dequeue() { double x; if (empty()) { cout << "Error: the queue is empty." << endl; exit(1); // return false; } else { x = front->data; Node* nextNode = front->next; delete front; front = nextNode; front counter--; } 3 8 5 return x; }
front
40
41
are several different algorithms to implement Enqueue and Dequeue Nave way
When enqueuing, the front index is always fixed and the rear index moves forward in the array.
rear
rear
rear
3 front Enqueue(3)
3 front
3 front
Enqueue(6)
Enqueue(9)
42
Nave
way (contd)
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 rear rear = -1
6 front
Dequeue()
Dequeue()
43
better way
When enqueued, the rear index moves forward. When dequeued, the front index also moves forward by one element
(rear) (after 1 dequeue, and 1 enqueue) (after another dequeue, and 2 enqueues) (after 2 more dequeues, and 2 enqueues)
The problem here is that the rear index cannot move beyond the last element in the array.
44
a circular array When an element moves past the end of a circular array, it wraps around to the beginning, e.g.
How
45
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); private: int front; int rear; int counter; int maxSize; double* values; }; // front index // rear index // number of elements // size of array queue // element array
46
Attributes of Queue
front/rear: front/rear index counter: number of elements in the queue maxSize: capacity of the queue values: point to an array which stores elements of the queue
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
Operations of Queue
47
Queue constructor
Queue(int
size = 10)
Allocate a queue array of size. By default, size = 10. front is set to 0, pointing to the first element of the array rear is set to -1. The queue is empty initially.
Queue::Queue(int size /* = 10 */) { values = new double[size]; maxSize = size; front = 0; rear = -1; counter = 0; }
48
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 < maxSize) else }
true; false;
49
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) % maxSize; // insert new item values[rear] = x; // update counter counter++; // return true; } }
50
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 = (front + 1) % maxSize; // update counter counter--; // return true; } return x; }
51
void Queue::print() { cout << "front -->"; for (int i = 0; i < counter; i++) { if (i == 0) cout << "\t"; else cout << "\t\t"; cout << values[(front + i) % maxSize]; if (i != counter - 1) cout << endl; else cout << "\t<-- rear" << endl; } }
52
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; }
Using Queue
53
Results
based on array
54
Queue applications
When
jobs are sent to a printer, in order of arrival, a queue. Customers at ticket counters