Data Structures (BCA) 3rd Sem Previous Year Solved Question Paper 2022

Practice Mode:
5.

What is priority queue? Explain one-way list representation of priority queue.

Explanation

A priority queue is an abstract data structure that stores a collection of elements, each associated with a priority. The elements are typically retrieved in order of their priority, where elements with higher priorities are dequeued before elements with lower priorities. Priority queues are often used in various applications, such as task scheduling, graph algorithms (like Dijkstra's algorithm), and data compression, to efficiently manage elements based on their importance or urgency.

One way to represent a priority queue is using a singly linked list. In this representation, each element in the list has a value and a priority associated with it. The elements are stored in such a way that they are sorted by their priorities. Here's an example of how you can implement a priority queue using a singly linked list:

class PriorityQueueNode:

def __init__(self, value, priority):

self.value = value

self.priority = priority

self.next = None


class PriorityQueue:

def __init__(self):

self.head = None


 def enqueue(self, value, priority):

new_node = PriorityQueueNode(value, priority)

 

# If the priority queue is empty or the new node has higher priority than the head, insert at the beginning

if not self.head or priority > self.head.priority:

new_node.next = self.head

self.head = new_node

else:

current = self.head

while current.next and priority <= current.next.priority:

current = current.next

new_node.next = current.next

current.next = new_node



def dequeue(self):

if not self.head:

return None

else:

value = self.head.value

self.head = self.head.next

return value



def is_empty(self):

return self.head is None



In this implementation, the PriorityQueueNode class represents each element with its value and priority. The PriorityQueue class maintains the linked list, and elements are inserted in sorted order based on their priorities. When you dequeue an element, you get the element with the highest priority first.

This singly linked list representation allows you to efficiently manage elements in the priority queue, with elements organized by their priorities for easy retrieval.