Unit1 - 2 - CSB4117 Data Structure (Stack & Queue Concepts)
Unit1 - 2 - CSB4117 Data Structure (Stack & Queue Concepts)
INTRODUCTION
A stack is a list with the restriction that insertions and deletions can be performed in only
one position, namely, the end of the list, called the top. It follows Last-In-First-Out (LIFO)
principle.
OPERATIONS ON STACK
Top 50
40
30
20
10
Fig. 12.2 Stack model: only the top element is accessible
PUSH
The process of inserting a new element to the top of the stack is called push operation.
For every push operation the top is incremented by 1.
Top
20
Top 10 10
Top Empty Stack After After
inserting an inserting an
element 10 element 20
The process of deleting an element from the top of stack is called pop operation.
After every pop operation the top pointer is decremented by 1.
Top 30
20
Top 20
10 10
Top 10
Initial Stack After the After the
element 30 element 20
is deleted is deleted
Fig. 3.4 Pop Operations
EXCEPTIONAL CONDITIONS
Overflow
Top 50
40
30
20
10
Fig. 12.5 Full Stack (Size = 5)
Underflow
Top
IMPLEMENTATION OF STACKS
Array
Linked list
REVIEW QUESTIONS
INTRODUCTION
In this implementation each stack is associated with a top pointer, which is -1 for an empty
stack.
Push
To push an element X onto the stack, top pointer is incremented by 1 and then set:
Stack [top] = X.
Pop
To pop an element from the stack, the Stack [top] value is returned and the top pointer is
decremented by 1.
STACK FULL
int IsFull()
{
if(top == MAX - 1)
return 1;
else
return 0
}
STACK EMPTY
int IsEmpty()
{
if(top == -1)
return 1;
else
return 0;
}
PUSH
Routine to Push an Element on to the Stack
POP
Routine to Pop an Element from the Stack
void Pop()
{
if(IsEmpty())
printf("Stack Underflow...!\n");
else
{
printf("%d\n", Stack[top]);
top = top - 1;
}
}
PEEK
void Top()
{
if(IsEmpty())
printf("Stack Underflow...!\n");
else
printf("%d\n", Stack[top]);
}
Routine to Display Stack Elements
void Display()
{
int i;
if(IsEmpty())
printf("Stack Underflow...!\n");
else
{
}
}
REVIEW QUESTIONS
INTRODUCTION
In this implementation:
EMPTY LIST
IsEmpty()
Step 1 : Start.
Step 2 : If List = NULL goto Step 3 else goto Step 4.
Step 3 : Return 1 and Stop.
Step 4 : Return 0 and Stop.
Step 5 : Stop.
PUSH
Example
The general idea is shown in Figure. The dashed line represents the old pointer.
The push is NewNode
implemented as
an insertion into
the front of a
linked list, where List
the front serves
as the top of the
stack.
Push(10)
Push(20)
NewNode
List
Push(30)
NewNode
List
POP
Example
List
Fig. Initial Stack
Pop()
TempNode
List
TOP
Top is performed by examining the element in the first position of the list.
Example
List
Fig. Initial Stack
Top()
List
DISPLAY
Example
List
REVIEW QUESTIONS
APPLICATIONS OF STACK
Balancing symbols
Infix to postfix conversion
Evaluating postfix expression
Function calls
Towers of Hanoi
8 queens problem
REVIEW QUESTIONS
INTRODUCTION
Compilers check your programs for syntax errors, but frequently a lack of one symbol (such
as a missing brace or comment starter) will cause the compiler to spill out a hundred lines of
diagnostics without identifying the real error.
A useful tool in this situation is a program that checks whether everything is balanced. Thus,
every right brace, bracket, and parenthesis must correspond to their left counterparts. The sequence
[()] is legal, but [(]) is wrong. Obviously, it is not worthwhile writing a huge program for this, but it
turns out that it is easy to check these things. For simplicity, we will just check for balancing of
parentheses, brackets, and braces and ignore any other character that appears.
Make an empty stack.
Read characters until end of input.
If the character read is not a symbol to be balanced, ignore it.
If the character is an opening symbol like (, [, {, push it onto the stack.
If it is a closing symbol like ), ], }, then if the stack is empty report an error as “Missing
opening symbol”. Otherwise, pop the stack.
If the symbol popped is not the corresponding opening symbol, then report an error as
“Mismatched symbol”.
At end of input, if the stack is not empty report an error as “Missing closing symbol”.
Otherwise, report as “Symbols are balanced”.
EXAMPLES
16.2.1 (a+b)
( a + b )
( ( ( (
( ( a + b )
( ( ( (
( ( ( ( ( (
( a + b )
( ( ( (
16.2.4 (a+b]
( a + b ]
( ( ( (
INTRODUCTION
There are 3 different ways of representing the algebraic expression. They are:
Infix notation
Postfix notation
Prefix notation
INFIX NOTATION
In infix notation, the arithmetic operator appears between the two operands to which it is
being applied.
For example:
A/B+C
POSTFIX NOTATION
In postfix notation, the arithmetic operator appears directly after the two operands to which it
applies. It is also called as reverse polish notation.
For example:
((A/B) + C) AB/C+
PREFIX NOTATION
In prefix notation, the arithmetic operator is placed before the two operands to which it
applies. It is also called as polish notation.
For example:
((A/B) + C) +/ABC
REVIEW QUESTIONS
INTRODUCTION
To evaluate an arithmetic expression, first convert the given infix expression to postfix
expression and then evaluate the postfix expression using stack.
Not only can a stack be used to evaluate a postfix expression, but we can also use a stack to
convert an expression in standard form (otherwise known as infix) into postfix.
a+b*c+(d*e+f)*g
First, the symbol a is read, so it is passed through to the output. Then '+' is read and pushed
onto the stack. Next b is read and passed through to the output. The state of affairs at this juncture is
as follows:
Next a '*' is read. The top entry on the operator stack has lower precedence than '*', so
nothing is output and '*' is put on the stack. Next, c is read and output. Thus far, we have
The next symbol is a '+'. Checking the stack, we find that we will pop a '*' and place it on the
output, pop the other '+', which is not of lower but equal priority, on the stack, and then push the '+'.
The next symbol read is an '(', which, being of highest precedence, is placed on the stack.
Then d is read and output.
We continue by reading a '*'. Since open parentheses do not get removed except when a
closed parenthesis is being processed, there is no output. Next, e is read and output.
The next symbol read is a '+'. We pop and output '*' and then push '+'. Then we read and
output.
Now we read a ')', so the stack is emptied back to the '('. We output a '+'.
We read a '*' next; it is pushed onto the stack. Then g is read and output.
The input is now empty, so we pop and output symbols from the stack until it is empty.
EXAMPLE-II
a * b + (c – d / e)
a
Stack Output
* a
Stack Output
* ab
Stack Output
+ ab*
Stack Output
(
+ ab*
Stack Output
(
+ ab*c
Stack Output
-
(
+ ab*c
Stack Output
-
(
+ ab*cd
Stack Output
/
-
(
+ ab*cd
Stack Output
/
-
(
+ ab*cde
Stack Output
ab*cde/-+
Stack Output
REVIEW QUESTIONS
INTRODUCTION
The easiest way to do this is to use a stack. The algorithm uses a stack and is as follows:
EXAMPLE-I
ab*cde/-+
2
a b * c d 8 8 / 4
5 5 e 5 5
5
4 4 20 20 20 20 20
- +
1
20 21
REVIEW QUESTIONS
INTRODUCTION
A queue is list with the restrictions that insertion is done at one end (rear), whereas deletion is
performed at the other end (front). It follows First-In-First-Out (FIFO) principle.
OPERATIONS ON QUEUE
Enqueue - which inserts an element at the end of the list (called rear).
Dequeue - which deletes (and returns) the element at the start of the list (known as
front).
None 0 1 2 3 4
F R
The process of inserting a new element on to the rear of the queue is called enqueue
operation.
For every enqueue operation the rear pointer is incremented by 1.
10 20 30
0 1 2 3 4
F R
Fig. 20.4 Enqueue Operations
10.4 DEQUEUE
The process of deleting an element from the front of queue is called dequeue operation.
After every dequeue operation the front pointer is incremented by 1.
20 30
0 1 2 3 4
F R
Fig. 20.5 Dequeue Operations
EXCEPTIONAL CONDITIONS
Overflow
10 20 30 40 50
0 1 2 3 4
F R
Fig. 20.6 Full Queue (Size = 5)
Underflow
Attempt to delete an element, when the queue is empty is said to be underflow.
None 0 1 2 3 4
F R Fig. 20.7 Empty Queue
IMPLEMENTATION OF QUEUE
Array
Linked list
APPLICATIONS OF QUEUE
REVIEW QUESTIONS
INTRODUCTION
In this implementation each queue is associated with two pointers namely front and rear,
which is -1 for an empty queue.
Enqueue
To insert an element X onto the queue, the rear pointer is incremented by 1 and then
set:
Queue[rear] = X.
Dequeue
To delete an element from the queue, the Queue[front] value is returned and the front pointer
is incremented by 1.
QUEUE FULL
int IsFull()
{
if(rear == MAX - 1)
return 1;
else
return 0;
}
QUEUE EMPTY
int IsEmpty()
{
if(front == -1)
return 1;
else
return 0;
}
ENQUEUE
DEQUEUE
void Dequeue()
{
if(IsEmpty())
printf("Queue is Underflow...!\n");
else
{
printf("%d\n", Queue[front]);
if(front == rear)
front = rear = -1;
else
front = front + 1;
}
}
DISPLAY
void Display()
{
int i;
if(IsEmpty())
printf("Queue is Underflow...!\n");
else
{
for(i = front; i <= rear; i++)
printf("%d\t", Queue[i]);
printf("\n");
}
}
REVIEW QUESTIONS
INTRODUCTION
In this implementation:
EMPTY LIST
IsEmpty(List)
Step 1 : Start.
Step 2 : If List = NULL goto Step 3 else goto Step 4.
Step 3 : Return 1 and Stop.
Step 4 : Return 0 and Stop.
Step 5 : Stop.
ENQUEUE
Example
Enqueue(10)
NewNode
Front
Rear
Enqueue(20)
NewNode
Front Rear
Enqueue(30)
NewNode
Front Rear
Algorithm to Enqueue an Element on to the queue
Enqueue(e)
Step 1 : Start.
Step 2 : Set NewNode = addressof(Queue).
Step 3 : Set NewNodeElement = e.
Step 4 : Set NewNodeNext = NULL.
Step 5 : If Rear = NULL, then goto Step 6 else goto Step 7.
Step 6 : Set Front = Rear = NewNode and goto Step 9.
Step 7 : Set RearNext = NewNode.
Step 8 : Set Rear = NewNode.
Step 9 : Stop.
DEQUEUE
Example
Front Rear
Fig. Initial Queue
Dequeue()
TempNode
Front Rear
Dequque()
Step 1 : Start.
Step 2 : If IsEmpty(Front) = True, then goto Step 3 else goto Step 4. Step
3 : Display “Queue is Underflow…!” and goto Step 10.
Step 4 : Set TempNode = Front.
Step 5 : If Front = Rear goto Step 6 else goto Step 7.
Step 6 : Set Front = Rear = NULL and goto Step 8.
Step 7 : Set Front = FrontNext.
Step 8 : Display TempNodeElement.
Step 9 : Delete TempNode.
Step 10: Stop.
DISPLAY
Example
Front Rear
Display(List)
Step 1 : Start.
Step 2 : If IsEmpty(Front) = TRUE goto Step 3 else goto Step 4.
Step 3 : Display “Queue is Underflow…!” and goto Step 8.
Step 4 : Set Position = Front.
Step 5 : Repeat the Steps 6-7 until Position != NULL.
Step 6 : Display PositionElement.
Step 7 : Set Position = PositionNext.
Step 8 : Stop.
REVIEW QUESTIONS
INTRODUCTION
A circular queue is a queue whose start and end locations are logically connected with each
other. That means, the start location comes after the end location. If we continue to add elements in
a circular queue till its end location, then after the end location has been filled, the next element will
be added at the beginning of the queue.
As we can see in Fig. 23.2, the start location of the queue comes after its end location. Thus,
if the queue is filled till its capacity, i.e., the end location, then the start location will be checked for
space, and if it is empty, the new element will be added there.
Figure shows the different states of a circular queue during insert and delete operations.
Advantages
Circular queues remove one of the main disadvantages of array implemented queues in
which a lot of memory space is wasted due to inefficient utilization.
QUEUE FULL
IsFull()
Step 1 : Start.
Step 2 : If front = (rear + 1) % MAX goto Step 3 else goto Step 4.
Step 3 : Return 1 and Stop.
Step 4 : Return 0. Step
5 : Stop.
IsEmpty()
Step 1 : Start.
Step 2 : If front = -1 goto Step 3 else goto Step 4.
Step 3 : Return 1 and Stop.
Step 4 : Return 0. Step
5 : Stop.
ENQUEUE
Enqueue(ele)
Step 1 : Start.
Step 2 : If IsFull() = True goto Step 3 else goto Step 4.
Step 3 : Display message “Queue is Overflow…!” and goto Step 8.
Step 4 : Set rear = (rear + 1) % MAX.
Step 5 : Set CQueue[rear] = ele.
Step 6 : If front = -1 goto Step 7 else goto Step 8.
Step 7 : Set front = 0.
Step 8 : Stop.
DEQUEUE
Dequeue()
Step 1 : Start.
Step 2 : If IsEmpty() = True goto Step 3 else goto Step 4.
Step 3 : Display message “Queue is Underflow…!” and goto Step 8. Step
4 : Display CQueue[front].
Step 5 : If front = rear goto Step 6 else goto Step 7.
Step 6 : Set front = rear = -1 and goto Step 8.
Step 7 : Set front = (front + 1) % MAX.
Step 8 : Stop.
DISPLAY
Display()
Step 1 : Start.
Step 2 : If IsEmpty() = True goto Step 3 else goto Step 4.
Step 3 : Display message “Queue is Underflow…!” and goto Step 9. Step
4 : Set i = front.
Step 5 : Repeat Steps 6 to 7 while i != rear.
Step 6 : Display CQueue[i].
Step 7 : Set i = (i + 1) % MAX.
Step 8 : Display CQueue[i].
Step 9 : Stop.
REVIEW QUESTIONS
INTRODUCTION
A double-ended queue is a special type of queue that allows insertion and deletion of
elements at both ends, i.e., front and rear. In simple words, a double-ended queue can be referred as
a linear list of elements in which insertion and deletion of elements takes place at its two ends but
not in the middle. This is the reason why it is termed as double-ended queue or deque.
TYPES
Based on the type of restrictions imposed on insertion and deletion of elements, a double-
ended queue is categorized into two types:
1. Input-restricted deque
2. Output-restricted deque
Input-restricted Deque
It allows deletion from both the ends but restricts the insertion at only one end.
Output-restricted Deque
It allows insertion at both the ends but restricts the deletion at only one end.
OPERATIONS
As shown in Fig., insertion and deletion of elements is possible at both front and rear ends of
the queue. As a result, the following four operations are possible for a double-ended queue: