CENG205-Lecture5
CENG205-Lecture5
Data structures
Lecture 5:
Stacks and Queues
Stacks
A stack is an ordered lists in which insertions and deletions are made at one end
called the top.
Stacks
top
C top
top
B B B
top
A A A A
Towers of Hanoi
Object of the game is to move all the disks (animals) over to Tower 3.
But you cannot place a larger disk onto a smaller disk.
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Towers of Hanoi
Stack Operations
1. Pop()
2. Push(x)
3. Top()
4. IsEmpty()
• Push(2)
• Push(10)
• Pop()
• Push(7)
• Push(5)
• Top(): 5
• IsEmpty(): False
Array implementation of stack (pseudocode)
int A[10]
top -1 //empty stack
Push(x)
{
top top + 1
A[top] x
}
Pop()
{
top top – 1
}
For an empty stack, top is set to -1.
In push function, we increment top.
In pop, we decrement top by 1.
Array implementation of stack (pseudocode)
Top()
{
return A[top]
}
IsEmpty()
{
if(top == -1)
return true
else
return false
}
Stack
Data Structure
typedef struct{
int VALUE;
}element;
element stack[MAX_STACK_SIZE];
int top=-1;
Push Stack
3
More array implementation
Queues
rear
C
rear B
B
rear
A A A
front,rear front front
front
Queue is a list with the restriction that insertion can be made at one end (rear)
And deletion can be made at other end (front).
Built-in Operations for Queue
Enqueue(x) or Push(x)
Dequeue() or Pop()
Front(): Returns the element in the front without removing it.
IsEmpty(): Returns true or false as an answer.
IsFull()
Each operation takes constant time, therefore has O(1) time complexity.
Example
Enqueue(2)
Enqueue(5)
Enqueue(3)
Dequeue()→ 2
Front()→ 5
IsEmpty()→ False
Applications:
• Printer queue
• Process scheduling
Array implementation of queue (Pseudocode)
int A[10]
front -1
rear -1
IsEmpty(){
if (front == -1 && rear == -1)
return true
else
return false}
Enqueue(x){
if IsFull()
return
else if IsEmpty()
front rear 0
else
rear rear+1
A[rear] x
}
Array implementation of queue (Pseudocode)
Dequeue(){
if IsEmpty(){
return
else if (front == rear)
front rear -1
else{
front front+1
}
typedef struct{
int value;
}element;
element queue[MAX_QUEUE_SIZE];
int front = -1;
int rear = -1;
Add Queue
queue[++rear]=item;
}
Delete Queue
element dequeue()
{
if(front == -1) //is empty
return empty_queue(); //empty
return data;
}
Circular Queue
• More efficient queue representation
element dequeueCircular()
{
if(front == -1) //is empty
return empty_queue(); //empty
return data;
}
References
• http://www.mycodeschool.com/videos