RAA DS Unit 2 Final Print
RAA DS Unit 2 Final Print
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 1
UNIT – II
5. EMPTY(S). Return true if S is an empty stack; return false otherwise.
The following diagram represents the working of the Stack:
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 2
UNIT – II
3. Finished.
Return
The first step of this algorithm checks for an overflow condition. If such a
condition exists, then the insertion cannot be performed on the stack and appropriate
error message occurs.
The first step of this algorithm checks for an underflow condition. If such a
condition exists, then some appropriate action should take place
9 100
0 10
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 4
UNIT – II
An Array Implementation of Stacks
Every implementation of lists we have described works for stacks, since a stack
with its operations is a special case of a list with its operations. The linked-list
representation of a stack is easy, as PUSH and POP operate only on the header cell and
the first cell on the list. In fact, headers can be pointers or cursors rather than complete
cells, since there is no notion of position" for stacks, and thus no need to represent
position 1 in a way analogous to other positions. However, the array-based
implementation of lists we gave in Section 2.2 is not a particularly good one for stacks,
as every PUSH or POP requires moving the entire list up or down, thus taking time
proportional to the number of elements on the stack. A better arrangement for using an
array takes account of the fact that insertions and deletions occur only at the top. We
can anchor the bottom of the stack at the bottom (high-indexed end) of the array, and
let the stack grow towards the top (low-indexed end) of the array. A cursor called top
indicates the current position of the first stack element. This idea is shown in Fig. 2.17.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 5
UNIT – II
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 6
UNIT – II
EXAMPLE PROGRAM IN C TO IMPLEMENT STACK USING ARRAYS:
/*PROGRAM FOR IMPLEMENTATION OF STACK USING ARRAY*/
#include<stdio.h>
#include<conio.h>
#define maxsize 5
int stack[maxsize],top; //declaration of stack and top of the stack
int stack_full(); //function declaration of stack_full() function
int stack_empty(); //function declaration of stack_empty() function
void push(int);
int pop();
void stack_display(); //function declaration of stack_display() function
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 9
UNIT – II
Linked list implementation of stack
Instead of using array, we can also use linked list to implement stack. Linked list
allocates the memory dynamically. However, time complexity in both the scenario is
same for all the operations i.e. push, pop and peek.
In linked list implementation of stack, the nodes are maintained 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.
The top most node in the stack always contains null in its address field. Lets discuss the
way in which, each operation is performed in linked list implementation of stack.
Adding a node to the stack (Push operation)
Adding a node to the stack is referred to as push operation. Pushing an element to a
stack in linked list implementation is different from that of an array implementation. In
order to push an element onto the stack, the following steps are involved.
1. Create a node first and allocate memory to it.
2. If the list is empty then the item is to be pushed as the start node of the list. This
includes assigning value to the data part of the node and assign null to the
address part of the node.
3. If there are some nodes in the list already, then we have to add the new element
in the beginning of the list (to not violate the property of the stack). For this
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 10
UNIT – II
purpose, assign the address of the starting element to the address field of the
new node and make the new node, the starting node of the list.
C implementation:
1. void push ()
2. {
3. int val;
4. struct node *ptr =(struct node*)malloc(sizeof(struct node));
5. if(ptr == NULL)
6. {
7. printf("not able to push the element");
8. }
9. else
10. {
11. printf("Enter the value");
12. scanf("%d",&val);
13. if(head==NULL)
14. {
15. ptr->val = val;
16. ptr -> next = NULL;
17. head=ptr;
18. }
19. else
20. {
21. ptr->val = val;
22. ptr->next = head;
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 11
UNIT – II
23. head=ptr;
24.
25. }
26. printf("Item pushed");
27.
28. }
29. }
Disadvantages of Stack
1. The Insertion and Deletion of the items in the stack can be done only at one end.
2. The element being inserted first has to wait for the longest time to get popped off
from the stack.
3. Only the element at the top of the stack can be deleted at a time.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 17
UNIT – II
APPLICATIONS OF STACK
1. Reversing a String or a number.
2. Expression Conversion.
3. Expression evaluations.
4. Parsing well formatted parenthesis.
5. Recursion
Other Stack application includes:
1. For example, as processor executes a program, when a function call is made, the
called function must know how to return back to the program, so the current
address of program execution is pushed onto a stack. Once the function is finished,
the address that was saved is removed from the stack, and execution of the
program resumes. If a series of function calls occur, the successive return values are
pushed onto the stack in LIFO order so that each function can return back to calling
program. Stacks support recursive function calls in the same manner as
conventional non recursive calls.
2. Stacks are used by compilers in the process of evaluating expressions & generating
machine code. They are also used to store return addresses in a chain of method
calls during execution of a program.
3. Real-time applications.
a) Direct applications.
The direct applications includes as:
Page-visited history in a Web browser.
Undo sequence in a text editor.
Saving local variables when one function calls another and this one
calls another, and so on.
b) Indirect applications
Auxiliary data structure for algorithms.
Component of other data structures.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 18
UNIT – II
QUEUES
INTRODUCTION
Queue is a linear data structure in which additions and deletions takes place at
different ends known as the Rear end and front end respectively. The end at which new
elements are added is called the rear, and the end from which elements are deleted is
called the front. A queue is a collection of items organized in a structure with the First-
In-First-Out (FIFO) property.
Definition:
“A queue is a (ordered) collection of items where all insertions are made to the
end of the sequence and all deletions always are made from the beginning of the
sequence”.
CONCEPT OF A QUEUE:
REAR FRONT
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 19
UNIT – II
The operations for a queue are analogous to those for a stack, the substantial
differences being that insertions go at the end of the list, rather than the beginning, and
that traditional terminology for stacks and queues is different. We shall use the
following operations on queues.
1. MAKENULL (Q) makes queue Q an empty list.
2. FRONT (Q) is a function that returns the first element on queue Q. FRONT (Q) can be
written in terms of list operations as RETRIEVE(FIRST(Q), Q).
3. ENQUEUE(x, Q) inserts element x at the end of queue Q. In terms of list operations,
ENQUEUE(x, Q) is INSERT(x, END(Q), Q).
4. DEQUEUE (Q) deletes the first element of Q; that is, DEQUEUE(Q) is
DELETE(FIRST(Q), Q).
5. EMPTY (Q) returns true if and only if Q is an empty queue.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 20
UNIT – II
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 21
UNIT – II
In the above figure, Join (36) adds a new element to the rear end of the queue
and as the element 36 enters the queue, the rear pointer is shifted to point the end of
the queue (i.e. rear points to element 36.)
In the second case, Leave function deletes the element 12 fro the front end of the
queue. Now since element 12 is deleted, the next element 7 is at the front end of the
queue.
#include<conio.h>
#include<stdio.h>
#define qmax 3
void qinsert(int);
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 22
UNIT – II
void qdelete();
void qdisplay();
int Q[qmax],front=0,rear=0,item,ch;
void main()
{
clrscr();
do
{
printf("\n\n\t--QUEUE--OPERATION--\n");
printf("\n\n\t1.INSERT--\n");
printf("\n\n\t2.DELETE\n");
printf("\n\n\t3.DISPLAY\n");
printf("\n\n\t4.EXIT\n");
printf("\n\tEnter Your choice:-\t");
scanf("%d",&ch);
switch(ch)
{
case 1:
qinsert(item);
break;
case 2:
qdelete();
break;
case 3:
qdisplay();
break;
case 4:
exit(0);
break;
default:
printf("\n\n\tINVALID CHOICE??????\n\n");
break;
}
}
while(ch!=4);
getch();
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 23
UNIT – II
}
void qinsert(int item)
{
if(rear==qmax)
{
printf("\n\n\t OVERFLOW!!\n");
}
else
{
printf("\n\n\t Enter the element:-\t");
scanf("%d",&item);
rear=rear+1;
Q[rear]=item;
printf("\n\t Element Inserted!!\n");
}
if(front==0)
{
front=front+1;
}
}
void qdelete()
{
if(front==0)
{
printf("\n\n\tUNDERFLOW!!\n");
}
item=Q[front];
printf("\n\tElement deleted!\n");
if(front==rear)
{
front=0;
rear=0;
}
else
front=front+1;
}
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 24
UNIT – II
void qdisplay()
{
int i;
printf("\n\n\t--QUEUE-ELEMENT--\n\n");
printf("\n\t");
for(i=front;i<=rear;i++)
{
printf("%d\t",Q[i]);
}
}
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 25
UNIT – II
Linked List implementation of Queue
Due to the drawbacks discussed in the previous section of this tutorial, the array
implementation cannot be used for the large scale applications where the queues are
implemented. One of the alternatives of array implementation is linked list
implementation of queue. The storage requirement of linked representation of a queue
with n elements is o(n) while the time requirement for operations is o(1).
In a linked queue, each node of the queue consists of two parts i.e. data part and the link
part. Each element of the queue points to its immediate next element in the memory.
In the linked queue, there are two pointers maintained in the memory i.e. front pointer
and rear pointer. The front pointer contains the address of the starting element of the
queue while the rear pointer contains the address of the last element of the queue.
Insertion and deletions are performed at rear and front end respectively. If front and
rear both are NULL, it indicates that the queue is empty.
The linked representation of queue is shown in the following figure.
Insert operation
The insert operations append the queue by adding an element to the end of the queue.
The new element will be the last element of the queue.
Firstly, allocate the memory for the new node ptr by using the following statement.
Ptr = (struct node *) malloc (sizeof(struct node));
There can be the two scenario of inserting this new node ptr into the linked queue.
In the first scenario, we insert element into an empty queue. In this case, the
condition front = NULL becomes true. Now, the new element will be added as the only
element of the queue and the next pointer of front and rear pointer both, will point to
NULL.
1. ptr -> data = item;
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 26
UNIT – II
2. if(front == NULL)
3. {
4. front = ptr;
5. rear = ptr;
6. front -> next = NULL;
7. rear -> next = NULL;
8. }
In the second case, the queue contains more than one element. The condition front =
NULL becomes false. In this scenario, we need to update the end pointer rear so that the
next pointer of rear will point to the new node ptr. Since, this is a linked queue, hence
we also need to make the rear pointer point to the newly added node ptr. We also need
to make the next pointer of rear point to NULL.
1. rear -> next = ptr;
2. rear = ptr;
3. rear->next = NULL;
In this way, the element is inserted into the queue. The algorithm and the C
implementation is given as follows.
Algorithm
o Step 1: Allocate the space for the new node PTR
o Step 2: SET PTR -> DATA = VAL
o Step 3: IF FRONT = NULL
SET FRONT = REAR = PTR
SET FRONT -> NEXT = REAR -> NEXT = NULL
ELSE
SET REAR -> NEXT = PTR
SET REAR = PTR
SET REAR -> NEXT = NULL
[END OF IF]
o Step 4: END
C Function
1. void insert(struct node *ptr, int item; )
2. {
3.
4.
5. ptr = (struct node *) malloc (sizeof(struct node));
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 27
UNIT – II
6. if(ptr == NULL)
7. {
8. printf("\nOVERFLOW\n");
9. return;
10. }
11. else
12. {
13. ptr -> data = item;
14. if(front == NULL)
15. {
16. front = ptr;
17. rear = ptr;
18. front -> next = NULL;
19. rear -> next = NULL;
20. }
21. else
22. {
23. rear -> next = ptr;
24. rear = ptr;
25. rear->next = NULL;
26. }
27. }
28. }
Deletion
Deletion operation removes the element that is first inserted among all the queue
elements. Firstly, we need to check either the list is empty or not. The condition front ==
NULL becomes true if the list is empty, in this case , we simply write underflow on the
console and make exit.
Otherwise, we will delete the element that is pointed by the pointer front. For this
purpose, copy the node pointed by the front pointer into the pointer ptr. Now, shift the
front pointer, point to its next node and free the node pointed by the node ptr. This is
done by using the following statements.
1. ptr = front;
2. front = front -> next;
3. free(ptr);
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 28
UNIT – II
The algorithm and C function is given as follows.
Algorithm
o Step 1: IF FRONT = NULL
Write " Underflow "
Go to Step 5
[END OF IF]
o Step 2: SET PTR = FRONT
o Step 3: SET FRONT = FRONT -> NEXT
o Step 4: FREE PTR
o Step 5: END
C Function
1. void delete (struct node *ptr)
2. {
3. if(front == NULL)
4. {
5. printf("\nUNDERFLOW\n");
6. return;
7. }
8. else
9. {
10. ptr = front;
11. front = front -> next;
12. free(ptr);
13. }
14. }
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 29
UNIT – II
8. struct node *front;
9. struct node *rear;
10. void insert();
11. void delete();
12. void display();
13. void main ()
14. {
15. int choice;
16. while(choice != 4)
17. {
18. printf("\n*************************Main Menu*****************************\
n");
19. printf("\n===================================================
==============\n");
20. printf("\n1.insert an element\n2.Delete an element\n3.Display the queue\n
4.Exit\n");
21. printf("\nEnter your choice ?");
22. scanf("%d",& choice);
23. switch(choice)
24. {
25. case 1:
26. insert();
27. break;
28. case 2:
29. delete();
30. break;
31. case 3:
32. display();
33. break;
34. case 4:
35. exit(0);
36. break;
37. default:
38. printf("\nEnter valid choice??\n");
39. }
40. }
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 30
UNIT – II
41. }
42. void insert()
43. {
44. struct node *ptr;
45. int item;
46.
47. ptr = (struct node *) malloc (sizeof(struct node));
48. if(ptr == NULL)
49. {
50. printf("\nOVERFLOW\n");
51. return;
52. }
53. else
54. {
55. printf("\nEnter value?\n");
56. scanf("%d",&item);
57. ptr -> data = item;
58. if(front == NULL)
59. {
60. front = ptr;
61. rear = ptr;
62. front -> next = NULL;
63. rear -> next = NULL;
64. }
65. else
66. {
67. rear -> next = ptr;
68. rear = ptr;
69. rear->next = NULL;
70. }
71. }
72. }
73. void delete ()
74. {
75. struct node *ptr;
76. if(front == NULL)
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 31
UNIT – II
77. {
78. printf("\nUNDERFLOW\n");
79. return;
80. }
81. else
82. {
83. ptr = front;
84. front = front -> next;
85. free(ptr);
86. }
87. }
88. void display()
89. {
90. struct node *ptr;
91. ptr = front;
92. if(front == NULL)
93. {
94. printf("\nEmpty queue\n");
95. }
96. else
97. { printf("\nprinting values .....\n");
98. while(ptr != NULL)
99. {
100. printf("\n%d\n",ptr -> data);
101. ptr = ptr -> next;
102. }
103. }
104. }
Output:
***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Enter your choice ?1
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 32
UNIT – II
Enter value?
123
***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Enter your choice ?1
Enter value?
90
***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Enter your choice ?3
printing values .....
123
90
***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
Enter your choice ?2
***********Main Menu**********
==============================
1.insert an element
2.Delete an element
3.Display the queue
4.Exit
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 33
UNIT – II
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 34
UNIT – II
Applications of Queue
The queue is also very general-purpose container and it can be used in various
applications. The simplest application of queue is where we need a data storage where
data items are waiting for further processing and processed in the in the order “they
came in”.
Queues are frequently used in operating systems and networking software
modules.
Job-Scheduling.
Processor queue.
Network router queues of outgoing packets, etc.
Maintain chronological order of print jobs or transactions while waiting for one
to complete.
Simulate retail or bank operations such as withdrawing cash from an ATM
machine.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 35
UNIT – II
Disadvantages of Queue
1. Only the elements at the front end of the queue can be deleted.
2. Insertion of the elements can be done at the rear end only.
3. Memory space is not effectively used in Array Implementation. There will be
empty spaces created on the Front side on deletion. But, the Linear Queue is
considered Full when the Rear reaches the last position. As a result, the empty
spaces in the Front are not utilized until the queue becomes empty.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 36
UNIT – II
Fig.: Circular Queue
In this Circular queue, once the queue is full, the “first” element of the queue
becomes the “rear” most element of the queue. Initially when the queue is empty ”front”
and ”rear” values are 0 and -1. Queue has got null values to all its elements. Every time
when we add an element to the queue, the ”rear” value increments by one till the time it
reaches the upper limit of the queue after which it starts all over again from 0. Here the
condition front>rear wont work
There is a formula which has to be applied for setting the front and rear pointers,
for a circular queue.
REAR + (REAR + 1) % SIZE OF QUEUE
FRONT + (FRONT + 1) % SIZE OF QUEUE
#include<conio.h>
#include<stdio.h>
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 37
UNIT – II
#define qmax 3
void qinsert();
void qdelete();
void qdisplay();
int Q[qmax],front=0,rear=0,item,ch;
void main()
{
clrscr();
do
{
printf("\ncircular queue\n");
printf("1.inserting\n");
printf("2.deleting\n");
printf("3.display\n");
printf("4.exit\n");
printf("Enter Your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
qinsert();
break;
case 2:
qdelete();
break;
case 3:
qdisplay();
break;
case 4:
exit(0);
break;
default:
printf("\ninvalid chice");
break;
}
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 38
UNIT – II
}
while(ch!=4);
getch();
}
void qinsert()
{
if((front==1 && rear==qmax)||(front==rear+1))
{
printf("\noverflow");
}
else
{
if(front==0)
{
front=1;
rear=1;
}
else if(rear==qmax)
{
rear=1;
}
else
{
rear=rear+1;
}
printf("Enter the element:\n");
scanf("%d",&item);
Q[rear]=item;
printf("\nElement Inserted");
}
}
void qdelete()
{
if(front==0)
{
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 39
UNIT – II
printf("\nUnderflow");
}
else
{
item=Q[front];
if(front==rear)
{
front=0;
rear=0;
}
else if(front==qmax)
{
front=1;
}
else
{
front=front+1;
}
}
}
void qdisplay()
{
int i;
if(front==0)
{
printf("\n Underflow");
}
else if(rear<front)
{
for(i=1;i<=rear;i++)
{
printf("%d\t",Q[i]);
}
for(i=front;i<=qmax;i++)
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 40
UNIT – II
{
printf("%d\t",Q[i]);
}
}
else
{
for(i=front;i<=rear;i++)
{
printf("%d\t",Q[i]);
}
}
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 41
UNIT – II
PRIORITY QUEUE
It is a special type of queue in which the elements are arranged based on the priority. It
is a special type of queue data structure in which every element has a priority
associated with it. Suppose some elements occur with the same priority, they will be
arranged according to the FIFO principle. The representation of priority queue is shown
in the below image -
“A Queue in which we are able to insert or remove items from any position based
on some property (such as priority of the task to be processed) is often referred
to as priority queue.”
A priority can be conceptualized as a series of queues representing situations in
which it knows what priorities are associated with queue items.
Insertion in priority queue takes place based on the arrival, while deletion in the
priority queue occurs based on the priority. Priority queue is mainly used to implement
the CPU scheduling algorithms.
1, 3, 4, 8, 14, 22
All the values are arranged in ascending order. Now, we will observe how the priority
queue will look after performing the following operations:
poll(): This function will remove the highest priority element from the priority
queue. In the above priority queue, the '1' element has the highest priority, so it
will be removed from the priority queue.
add(2): This function will insert '2' element in a priority queue. As 2 is the
smallest element among all the numbers so it will obtain the highest priority.
poll(): It will remove '2' element from the priority queue as it has the highest
priority queue.
add(5): It will insert 5 element after 4 as 5 is larger than 4 and lesser than 8, so it
will obtain the third highest priority in a priority queue.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 43
UNIT – II
the largest number, i.e., 5 is given as the highest priority in a priority queue.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 44
UNIT – II
elements would be inserted based on the FIFO principle; therefore, 444 will be added
first, then 555, and then 777.
Step 4: After inserting the elements of priority 4, the next higher priority number is 5,
and the value associated with priority 5 is 666, so it will be inserted at the end of the
queue.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 46
UNIT – II
APPLICATIONS OF STACK
I.POLISH NOTATION
The Polish mathematician JAN ŁUKASIEWICZ made the observation that, by
writing all operators either before their operands or after them, it is not necessary to
keep track of priorities, of parentheses bracketing expressions, or to make repeated
scans to evaluate an expression.
An Expression is a string of operands and operators. Operands are some numeric
values and operator are of two types either unary or binary. There are three types of
expressions.
1. Infix Expression.
2. Postfix Expression.
3. Prefix Expression.
INFIX, POSTFIX & PREFIX EXPRESSIONS
Infix, Postfix and Prefix notations are three different but equivalent ways of
writing expressions. It is easiest to demonstrate the differences by looking at examples
of operators that take two operands.
Infix notation: X + Y
Operators are written in-between their operands. This is the usual way we write
expressions. An expression such as A * (B + C) / D is usually taken to mean something
like: "First add B and C together, then multiply the result by A, then divide by D to give
the final answer."
Infix notation needs extra information to make the order of evaluation of the
operators clear: rules built into the language about operator precedence and
associativity, and brackets ( ) to allow users to override these rules. For example, the
usual rules for associativity say that we perform operations from left to right, so the
multiplication by A is assumed to come before the division by D. Similarly, the usual
rules for precedence say that we perform multiplication and division before we perform
addition and subtraction.
(/ (* A (+ B C)) D)
Although Prefix "operators are evaluated left-to-right", they use values to their
right, and if these values themselves involve computations then this changes the order
that the operators have to be evaluated in. In the example above, although the division
is the first operator on the left, it acts on the result of the multiplication, and so the
multiplication has to happen before the division (and similarly the addition has to
happen before the multiplication).
Because Postfix operators use values to their left, any values involving
computations will already have been calculated as we go left-to-right, and so the order
of evaluation of the operators is not disrupted in the same way as in Prefix expressions.
In all three versions, the operands occur in the same order, and just the
operators have to be moved to keep the meaning correct. (This is particularly important
for asymmetric operators like subtraction and division: A - B does not mean the same as
B - A; the former is equivalent to A B - or - A B, the latter to B A - or - B A).
PRIORITIES OF OPERATORS
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 48
UNIT – II
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 49
UNIT – II
Example 1:
( (A * B) + (C / D) ) ( (A B *) (C D /) +) (+ (* A B) (/ C D) )
((A * (B + C) ) / D) ( (A (B C +) *) D /) (/ (* A (+ B C) ) D)
(A * (B + (C / D) ) ) (A (B (C D /) +) *) (* A (+ B (/ C D) ) )
You can convert directly between these bracketed forms simply by moving the
operator within the brackets e.g. (X + Y) or (X Y +) or (+ X Y). Repeat this for all the
operators in an expression, and finally remove any superfluous brackets.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 50
UNIT – II
Use of stack by Function call & Recursive call:
The function call requires a special data structure called “stack”. But a call to a
function can be of two types.
1. Recursive function call.
2. Non-Recursive function call / Iterative call.
TOWERS OF HANOI
INTRODUCTION
The Tower of Hanoi, a puzzle invented by French mathematician ´Edouard Lucas
in 1883, consists of three vertical pegs and some number n of disks, all with a hole in the
center that allows them to be stacked on the pegs. The disks are all of different radii, and
we imagine that they are numbered 1 through n in increasing order of size. They are
initially stacked in order on one of the pegs, with disk n on the bottom and 1 on the top.
The object is to transport this tower from the starting peg to a destination peg, moving
one disk at a time, and always placing a disk on either an empty peg or on a larger disk.
The third peg is used to temporarily hold disks during the process.
In the Towers of Hanoi problem, there are three posts and seven disks of
different sizes. Each disk has a hole through the center so that it fits on a post. At the
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 52
UNIT – II
start, all seven disks are on post #1 as shown below. The disks are arranged by size so
that the smallest is on top and the largest is on the bottom. The goal is to end up with all
seven disks in the same order, but on a different post. This is not trivial because of two
restrictions. First, the only permitted action is removing the top disk from a post and
dropping it onto another post. Second, a larger disk can never lie above a smaller disk
on any post. (These rules imply, for example, that it is no fair to pick up the whole stack
of disks at once and then to drop them all on another post!)
One approach to this problem is to consider a simpler variant with only three
disks. We can quickly exhaust the possibilities of this simpler puzzle and find a 7 move
solution such as the one shown below. (The disks on each post are indicated by the
numbers immediately to the right. Larger numbers correspond to larger disks.)
FINDING A RECURRENCE
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 53
UNIT – II
Step 1: Apply this strategy recursively to move the top n - 1 disk from the first post to
the third post. This can be done in Tn-1 steps.
Step 2: Move the largest disk from the first post to the second post. This requires just 1
step.
Step 3: Recursively move the n - 1 disk on the third post over to the second post. Again,
Tn-1 steps are required.
EXAMPLE:
Consider a problem with 3 disks as A, B and C and 3 pegs as 1, 2 and 3. The
following figure represents the initial and final state of the problem.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 54
UNIT – II
There are 3 pegs ‘from’, ‘using ‘and ‘to’. Some disks of different sizes are given
which can slide onto any peg. Initially all of those are in ‘from’ peg in order of size with
largest disk at the bottom and smallest disk at the top. We have to move all the disks
from ‘from’ peg to ‘to’ peg. At the end,’ to’ peg will have disks in the same order of size.
There are some rules:
1) Only one disk can be moved from one peg to another peg at a time.
2) A disk can be placed only on top of a larger one.
3) A disk can be moved from top only.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 55
UNIT – II
Time Complexity:
Let the time required for n disks is T(n). There are 2 recursive call for n-1 disks
and one constant time operation to move a disk from ‘from’ peg to ‘to’ peg. Let it be k
1.
Therefore,
T(n) = 2 T(n-1) + k
1
T(0) = k , a constant.
2
T(1) = 2 k + k
2 1
T(2) = 4 k + 2k + k
2 1 1
T(2) = 8 k + 4k + 2k + k
2 1 1 1
n
Coefficient of k1 =2
n
Coefficient of k2 =2 -1
n n
Time complexity is O(2 ) or O(a ) where a is a constant greater than 1. So it has
exponential time complexity. For single increase in problem size the time required is
double the previous one. This is computationally very expensive. Most of the recursive
programs take exponential time that is why it is very hard to write them iteratively.
Space Complexity:
Space for parameter for each call is independent of n i.e., constant. Let it be k.
nd st
When we do the 2 recursive call 1 recursive call is over. So, we can reuse the space of
st nd
1 call for 2 call.
Hence,
T(n) = T(n-1) + k
T(0) = k
T(1) = 2k
T(2) = 3k
T(3) = 4k
So the space complexity is O(n). Here time complexity is exponential but space
complexity is linear. Often there is a trade off between time and space complexity.
S.Y. B.Tech., CSE (Data Science), SSGBCOET, Bsl, Data Structures, UNIT – II Notes by Prof. R. A. Agrawal. Page 56