Stack and Queue: COMP171 Fall 2005
Stack and Queue: COMP171 Fall 2005
Fall 2005
Stack Overview
Stack ADT
Basic operations of stack
Pushing, popping etc.
Implementations of stacks using
array
linked list
Stack and Queue / Slide 3
Stack ADT
Stacks are less flexible
but are more efficient and easy to implement
Stacks are known as LIFO (Last In, First Out)
lists.
The last element inserted will be the first to be
retrieved
Stack and Queue / Slide 5
top
B
top top A
A A
top
Stack and Queue / Slide 6
Implementation of Stacks
Any list implementation could be used to
implement a stack
Arrays (static: the size of stack is given initially)
Linked lists (dynamic: never become full)
We will explore implementations based on
array and linked list
Let’s see how to use an array to implement a
stack first
Stack and Queue / Slide 7
Array Implementation
Need to declare an array size ahead of time
Associated with each stack is TopOfStack
for an empty stack, set TopOfStack to -1
Push
(1) Increment TopOfStack by 1.
(2) Set Stack[TopOfStack] = X
Pop
(1) Set return value to Stack[TopOfStack]
(2) Decrement TopOfStack by 1
These operations are performed in very fast constant time
Stack and Queue / Slide 8
Stack class
class Stack {
public:
Stack(int size = 10); // constructor
~Stack() { delete [] values; } // destructor
bool IsEmpty() { return top == -1; }
bool IsFull() { return top == maxTop; }
double Top();
void Push(const double x);
double Pop();
void DisplayStack();
private:
int maxTop; // max stack size = size - 1
int top; // current top of stack
double* values; // element array
};
Stack and Queue / Slide 9
Stack class
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
IsEmpty: return true if stack is empty, return false otherwise
IsFull: 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
DisplayStack: print all the data in the stack
Stack and Queue / Slide 10
Create Stack
The constructor of Stack
Allocate a stack array of size. By default,
size = 10.
When the stack is full, top will have its maximum
value, i.e. size – 1.
Initially top is set to -1. It means the stack is empty.
Stack::Stack(int size /*= 10*/) {
maxTop = size - 1;
values = new double[size];
top = -1;
}
Push Stack
void Push(const double x);
Push an element onto the stack
If the stack is full, print the error information.
Note top always represents the index of the top
element. After pushing an element, increment top.
Pop Stack
double Pop()
Pop and return the element at the top of the stack
If the stack is empty, print the error information. (In
this case, the return value is useless.)
Don’t forgot to decrement top
double Stack::Pop() {
if (IsEmpty()) {
cout << "Error: the stack is empty." << endl;
return -1;
}
else {
return values[top--];
}
}
Stack and Queue / Slide 13
Stack Top
double Top()
Return the top element of the stack
Unlike Pop, this function does not remove the top
element
double Stack::Top() {
if (IsEmpty()) {
cout << "Error: the stack is empty." << endl;
return -1;
}
else
return values[top];
}
Stack and Queue / Slide 14
void Stack::DisplayStack() {
cout << "top -->";
for (int i = top; i >= 0; i--)
cout << "\t|\t" << values[i] << "\t|" << endl;
cout << "\t|---------------|" << endl;
}
Stack and Queue / Slide 15
Using Stack
result
int main(void) {
Stack stack(5);
stack.Push(5.0);
stack.Push(6.5);
stack.Push(-3.0);
stack.Push(-8.0);
stack.DisplayStack();
cout << "Top: " << stack.Top() << endl;
stack.Pop();
cout << "Top: " << stack.Top() << endl;
while (!stack.IsEmpty()) stack.Pop();
stack.DisplayStack();
return 0;
}
Stack and Queue / Slide 16
Balancing Symbols
To check that every right brace, bracket, and parentheses
must correspond to its left counterpart
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
Stack and Queue / Slide 19
Postfix Expressions
Calculate 4.99 * 1.06 + 5.99 + 6.99 * 1.06
Need to know the precedence rules
Postfix (reverse Polish) expression
4.99 1.06 * 5.99 + 6.99 1.06 * +
Use stack to evaluate postfix expressions
When a number is seen, it is pushed onto the stack
When an operator is seen, the operator is applied to the 2
numbers that are popped from the stack. The result is
pushed onto the stack
Example
evaluate 6 5 2 3 + 8 * + 3 + *
The time to evaluate a postfix expression is O(N)
processing each element in the input consists of stack
operations and thus takes constant time
Stack and Queue / Slide 20
Stack and Queue / Slide 21
Queue Overview
Queue ADT
Basic operations of queue
Enqueuing, dequeuing etc.
Implementation of queue
Array
Linked list
Stack and Queue / Slide 22
Queue ADT
Like a stack, a queue is also a list. However,
with a queue, insertion is done at one end,
while deletion is performed at the other end.
Accessing the elements of queues follows a
First In, First Out (FIFO) order.
Like customers standing in a check-out line in a
store, the first customer in is the first customer
served.
Stack and Queue / Slide 23
Remove Insert
(Dequeue) front rear (Enqueue)
Stack and Queue / Slide 25
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
Stack and Queue / Slide 26
3 3 6 3 6 9
6 9 9
Empty or Full?
Empty queue
back = front - 1
Full queue?
the same!
Reason: n values to represent n+1 states
Solutions
Use a boolean variable to say explicitly whether the queue is
empty or not
Make the array of size n+1 and only allow n elements to be
stored
Use a counter of the number of elements in the queue
Stack and Queue / Slide 32
Queue Class
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
Operations of Queue
IsEmpty: return true if queue is empty, return false otherwise
IsFull: 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
DisplayQueue: print all the data
Stack and Queue / Slide 34
Create Queue
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;
}
Stack and Queue / Slide 35
Enqueue
bool Queue::Enqueue(double x) {
if (IsFull()) {
cout << "Error: the queue is full." << endl;
return false;
}
else {
// calculate the new rear position (circular)
rear = (rear + 1) % maxSize;
// insert new item
values[rear] = x;
// update counter
counter++;
return true;
}
}
Stack and Queue / Slide 37
Dequeue
bool Queue::Dequeue(double & x) {
if (IsEmpty()) {
cout << "Error: the queue is empty." << endl;
return false;
}
else {
// retrieve the front item
x = values[front];
// move front
front = (front + 1) % maxSize;
// update counter
counter--;
return true;
}
}
Stack and Queue / Slide 38
void Queue::DisplayQueue() {
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;
}
}
Stack and Queue / Slide 39
Using Queue
int main(void) {
Queue queue(5);
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.DisplayQueue();
double value;
queue.Dequeue(value);
cout << "Retrieved element = " << value << endl;
queue.DisplayQueue();
queue.Enqueue(7);
queue.DisplayQueue();
return 0;
}
Stack and Queue / Slide 40
Enqueue
void Queue::Enqueue(double x) {
Node* newNode = new Node;
newNode->data = x;
newNode->next = NULL;
if (IsEmpty()) {
front = newNode;
rear = newNode;
} rear
else { 8 5
rear->next = newNode;
rear = newNode;
rear
}
counter++; 8 5
} newNode
Stack and Queue / Slide 42
Dequeue
bool Queue::Dequeue(double & x) {
if (IsEmpty()) {
cout << "Error: the queue is empty." << endl;
return false;
}
else {
x = front->data;
Node* nextNode = front->next;
delete front;
front = nextNode;
counter--;
} front
}
3 8 5
front
8 5
Stack and Queue / Slide 43
Result
Queue implemented using linked list will be
never full