Unit 3
Unit 3
Unit 3
• Always new items are added at top of the stack and also
removed from the top of the stack only.
• Easy to implement
• Create fixed size one dimensional array
– insert or delete the elements into the array using LIFO
principle using the variable 'top‘
Stack - top
• About top
• The stack implemented using linked list can work for the
variable size of data. So, there is no need to fix the size at
the beginning of the implementation
Stack – Linked list
• Dynamic Memory allocation of Linked list is
followed
• The nodes are scattered and
non-contiguously in the memory
• Each node contains a pointer to its immediate
successor node in the stack
• Stack is said to be overflown if the space left
in the memory heap is not enough to create a
node
Stack – Linked list
• In linked list implementation of a stack, every new
element is inserted as 'top' element.
• That means every newly inserted element is pointed by
'top'.
• To remove an element from the stack, simply remove the
node which is pointed by 'top' by moving 'top' to its
previous node in the list.
• The next field of the First element must be
always NULL.
Example Stack – Linked List
(A + B) / D /+ABD AB+D/
(A + B) / (D + E) /+AB+DE AB+DE+/
(A - B / C + E)/(A + B) / + - A / B C E + A B ABC/-E+AB+/
B ^2 - 4 * A * C -^B2**4AC B2^4A*C*-
Why postfix representation of the
expression?
• Infix expressions are readable and solvable by humans
because of easily distinguishable order of operators, but
compiler doesn't have integrated order of operators.
a + b *c +d
The expression is
(A+B) + (C-D) Yes having balanced
symbol
1. https://www.tutorialspoint.com/data_structures_algorithms/stack_algorithm.htm
2. https://www.codesdope.com/course/data-structures-stacks/
3. http://www.firmcodes.com/write-a-c-program-to-implement-a-stack-using-an-array-and-link
ed-list/
4. http://www.btechsmartclass.com/data_structures/stack-using-linked-list.html
5. http://www.exploredatabase.com/2018/01/stack-abstract-data-type-data-structure.html
6. https://www.geeksforgeeks.org/stack-set-2-infix-to-postfix/
7. https://www.hackerearth.com/practice/notes/stacks-and-queues/
8. https://github.com/niinpatel/Parenthesis-Matching-with-Reduce-Method
9. https://www.studytonight.com/data-structures/stack-data-structure
10. https://www.programming9.com/programs/c-programs/230-c-program-to-convert-infix-to-p
ostfix-expression-using-stack
SESSION 6
Applications of Stack: Function Call and
Return
• 2 types of Memory
– Stack
– Heap
• Stack memory stores the data (variables) related to
each function.
• Why is it called stack memory?
– The last function to be called is the first to return (LIFO)
– The data related to a function are pushed into the stack
when a function is called and popped when the function
returns
Function Calls
• Function calls another function
->We are executing function A. In the course of
its execution, function A calls another function B.
Function B in turn calls another function C, which
calls function D.
Function A
Function B
Function C
Function D
• When A calls B, A is pushed on top of the system stack.
When the
execution of B is complete, the system control will remove A
from
the stack and continue with its execution.
• When B calls C, B is pushed on top of the system stack.
When the
execution of C is complete, the system control will remove B
from
the stack and continue with its execution.
• When C calls D, C is pushed on top of the system stack.
When the
execution of D is complete, the system control will remove C
from
the stack and continue with its execution.
• When D calls E, D is pushed on top of the system stack.
When the
execution of E is complete, the system control will remove D
from
the stack and continue with its execution.
• When E has executed, D will be removed for execution.
• When C has executed, B will be removed for execution.
• When D has executed, C will be removed for execution.
• When B has executed, A will be removed for execution.
Nested Function Calls
• Consider the code snippet below:
main() foo() bar()
{ { {
... ... ...
foo(); bar(); }
...
bar(); }
}
Nested Function Calls and Returns in
Stack Memory
• Stack memory when the code executes:
fact(4);
A B
C
• All disks from peg A have to be transferred to
peg C
Towers of Hanoi Solution for 3 disks
Image Source:
https://www.includehelp.com/data-structure-tutorial/tower-of-hanoi-using-recu
rsion.aspx
Towers of Hanoi – Recursive Solution
/* N = Number of disks
Beg, Aux, End are the pegs */
https://www.javatpoint.com/array-representation-of-queue
Enqueue in Array Implementation of
Queue
//Basic Idea
Time Complexity:
enqueue(num): O(1)
rear++
queue[rear]=num
return
Dequeue in Array Implementation of
Queue
//Basic Idea Time Complexity: O(1)
O(n) if elements are
dequeue(): shifted
num = queue[front]
front++
return num
Enqueue and Dequeue in Queue
https://www.tutorialride.com/data-structures/queue-in-data-structur
e.htm
• No more insertion is possible (since rear
cannot be incremented anymore) even though
2 spaces are free.
• Workaround: Circular Queue, Shifting
elements after each dequeue
Linked List Implementation of Queue
Image Source:
Dequeue Operation in Linked List
Implementation of Queue
• Dequeue basic code: Time Complexity:
ptr = front; O(1)
Fro
nt
Image Source:
https://learnersbucket.com/tutorials/data-structures/implement-queue-using-l
inked-list/
References
• Seymour Lipschutz, Data Structures, Schaum’s
Outlines, 2014.
SESSION 11
Circular Queue
CIRCULAR QUEUES
• Circular Queue is a linear data structure
in which the operations are performed
based on FIFO (First In First Out) principle
and the last position is connected back to
the first position to make a circle. It is
also called ‘Ring Buffer’.
• In a normal Queue, we can insert
elements until queue becomes full. But
once queue becomes full, we can not
insert the next element even if there is a
space in front of queue.
• Deletions and insertions can only be
performed at front and rear end
respectively, as far as linear queue is
concerned.
CIRCULAR QUEUES
• However, if we delete 2 elements at the
Consider the queue shown in the following figure.
front end of the queue, we still can not
insert any element since the condition
rear = max -1 still holds.
• This is the main problem with the linear
queue, although we have space available
in the array, but we can not insert any
more element in the queue. This is
simply the memory wastage and we
need to overcome this problem.
• The Queue shown in above figure is
completely filled and there can't be
inserted any more element due to the
condition rear == max - 1 becomes
true.
• One of the solution of this problem is
circular queue. In the circular queue,
the first index comes right after the
last index. You can think of a circular
queue as shown in the following
CIRCULAR QUEUES
• One of the solution of this problem is
circular queue. In the circular queue,
the first index comes right after the
last index. You can think of a circular • Circular queue will be full when
queue as shown in the following front = -1 and rear = max-1.
figure. Implementation of circular queue is
similar to that of a linear queue.
Only the logic part that is
implemented in the case of
insertion and deletion is different
from that in a linear queue.
CIRCULAR QUEUE OPERATIONS
Algorithm to insert an element in circular
Insertion in Circular queue queue
• There are three scenario of inserting Step 1: IF (REAR+1)%MAX = FRONT
an element in a queue. Write " OVERFLOW "
• If (rear + 1)%maxsize = front, the Goto step 4
queue is full. In that case, overflow [End OF IF]
occurs and therefore, insertion can Step2:IF FRONT=-1andREAR=-1
not be performed in the queue. SET FRONT = REAR = 0
ELSE
• If rear != max - 1, then rear will be
incremented to the mod(maxsize) and IF REAR = MAX - 1 and FRONT ! = 0
the new value will be inserted at the SET REAR = 0
rear end of the queue. ELSE
SET REAR = (REAR + 1) % MAX
• If front != 0 and rear = max - 1, then it [END OF IF]
means that queue is not full Step 3: SET QUEUE[REAR] = VAL o Step 4:
therefore, set the value of rear to 0 EXIT
and insert the new element there.
CIRCULAR QUEUE OPERATIONS
Algorithm to delete an element in
Deletion in Circular queue circular queue
• To delete an element from the circular
queue, we must check for the three following Step 1: IF FRONT = -1
conditions. Write " UNDERFLOW " Goto Step
• If front = -1, then there are no elements in 4
the queue and therefore this will be the case [END of IF]
of an underflow condition.
• If there is only one element in the queue, in Step 2: SET VAL = QUEUE[FRONT]
this case, the condition rear = front holds and Step 3: IF FRONT = REAR
therefore, both are set to -1 and the queue is
deleted completely. SET FRONT = REAR = -1 ELSE
• If front = max -1 then, the value is deleted IF FRONT = MAX -1
from the front end the value of front is set to SET FRONT = 0
0. ELSE
• Otherwise, the value of front is incremented SET FRONT = FRONT + 1
by 1 and then delete the element at the front
end. [END of IF]
[END OF IF]
Step 4: EXIT
Operations Involved
• Enqueue
• Dequeue
Variables Used
• MAX- Number of entries in the array
• Front – is the index of front queue entry in an array
(Get the front item from queue)
• Rear – is the index of rear queue entry in an
array.(Get the last item from queue)
Concepts of Circular Queue
Illustration of Enqueue and Dequeue
Applications of Queue
• Queue, as the name suggests is used whenever we need to
manage any group of objects in an order in which the first
one coming in, also gets out first while the others wait for
their turn, like in the following scenarios:
• Serving requests on a single shared resource, like a printer,
CPU task scheduling etc.
• In real life scenario, Call Center phone systems uses Queues
to hold people calling them in an order, until a service
representative is free.
• Handling of interrupts in real-time systems. The interrupts
are handled in the same order as they arrive i.e First come
first served.
Review Questions
1. Explain the concept of a circular queue? How is it better than a linear queue?
2. Draw the queue structure in each case when the following operations are performed on an empty queue.
(a)Add A, B, C, D, E, F. (b) Delete two letters
(c) Add G (d) Add H
(e) Delete four letters (f) Add I
3. The circular queue will be full only when _____.
(a) FRONT=MAX-1 and REAR=MAX-1 (b) FRONT=0 and REAR=MAX-1
(c) FRONT=MAX-1 and REAR=0. (d) FRONT=0 and REAR=0
4. The function that deletes values from a queue is called ______.
(a) Enqueue (b)dequeue
(c) Pop (d) peek
5. New nodes are added at of the queue.
6. _________ allows insertion of elements at either ends but not in the middle.
7. A queue is a _____ data structure in which the element that is inserted first is the first one to be taken out.
8. In a circular queue, the first index comes after the ______ index.
9. In the computer’s memory, queues can be implemented using _________ and _______.
10. The storage requirement of linked representation of queue with n elements is ____ and the typical time
requirement for operations is _______.
Difference between Queue and Circular
Queue
• In a normal Queue, we can insert elements until
queue becomes full. But once queue becomes full, we
can not insert the next element even if there is a space
in front of queue.