Golang Program to Implement a Priority Queue Using a Linked List


A priority queue is a data structure where each element is assigned a priority and elements with higher priority are dequeued first. In this article, The Golang program focuses to implement a priority queue using a linked list. Here we are going to use seven different methods: PriorityQueue struct, Node struct, insert, remove, Isempty, size as well as peek along with examples to elaborate the concept.

Syntax

type PriorityQueue struct { head *Node}

The Syntax type PriorityQueue struct { ... } defines a struct type called PriorityQueue in Golang. It has one field: head of type *Node. The PriorityQueue struct is used to represent a priority queue, where the head field points to the first node in the linked list. This struct is used to maintain the overall structure of the priority queue and perform operations on it.

func (pq *PriorityQueue) Insert(value interface{}, priority int)

The Syntax func (pq *PriorityQueue) Insert(value interface{}, priority int) is a method declaration in Golang. It defines a method named Insert that operates on a PriorityQueue instance (receiver) represented by pq.

func (pq *PriorityQueue) Remove() interface{}

The Syntax func (pq *PriorityQueue) Remove() interface{} is another method declaration in Golang. It defines a method named Remove that operates on a PriorityQueue instance (receiver) represented by pq.

func (pq *PriorityQueue) IsEmpty() bool

This method checks if the priority queue represented by pq is empty by examining the head pointer. If the head pointer is nil, it means that there are no nodes in the linked list, and thus the priority queue is empty.

func (pq *PriorityQueue) Size() int

This method calculates the size of the priority queue by iterating through the linked list and counting the number of nodes. It starts from the head node and traverses each next pointer until reaching the end of the linked list.

func (pq *PriorityQueue) Peek() interface{}

This method allows you to peek at the element with the highest priority in the priority queue without removing it. It does so by accessing the value field of the head node, which represents the element at the front of the priority queue.

Algorithm

  • Define a struct type to represent the elements of the priority queue. Each element should have a value and a priority.

  • Create a struct type for the linked list node, which should contain a pointer to the element and a pointer to the next node.

  • Declare a variable to keep track of the head node of the linked list.

  • Implement a function to insert an element into the priority queue. This function should take the value and priority as parameters, create a new node with the element, and insert it into the appropriate position in the linked list based on its priority.

  • Implement a function to remove and return the element with the highest priority from the priority queue. This function should update the head node of the linked list and return the element.

  • Implement a function to check if the priority queue is empty by checking if the head node is nil.

  • Optional: Implement additional functions to retrieve the element with the highest priority without removing it, or to perform other operations on the priority queue as needed.

Example 1

In this example, we define a struct named Node that represents a node in the priority queue. It has three fields: value to store the value of the node, priority to represent the priority of the node, and next to point to the next node in the linked list.In the main function, we create a sample Node instance and initialize its fields. Then, we print the values of the node's fields using fmt.Println().

package main

import "fmt"

type Node struct {
   value    interface{}
   priority int
   next     *Node
}

func main() {

   node := &Node{
      value:    "Sample Value",
      priority: 1,
      next:     nil,
   }
	
   fmt.Println("Node Value:", node.value)
   fmt.Println("Node Priority:", node.priority)
   fmt.Println("Next Node:", node.next)
}

Output

Node Value: Sample Value
Node Priority: 1
Next Node: <nil>

Example 2

In this example, we define a struct named PriorityQueue that represents a priority queue. It has one field head which points to the head of the linked list.In the main function, we create a sample PriorityQueue instance and initialize its head field to nil. Then, we print the value of the head field using fmt.Println().

package main

import "fmt"

type Node struct {
   value    interface{}
   priority int
   next     *Node
}

type PriorityQueue struct {
   head *Node
}

func main() {
   pq := &PriorityQueue{
      head: nil,
   }
   fmt.Println("PriorityQueue Head:", pq.head)
}

Output

PriorityQueue Head: <nil>

Example 3

In this example, we define the Insert method for the PriorityQueue struct. The method takes a value and priority as input and inserts a new node with the given value and priority into the priority queue. In the main function, we create a sample PriorityQueue instance and insert three nodes with different values and priorities. Finally, we print the values and priorities of all the nodes in the priority queue to verify the insertion operation.

package main

import "fmt"

type Node struct {
   value    interface{}
   priority int
   next     *Node
}

type PriorityQueue struct {
   head *Node
}

func (pq *PriorityQueue) Insert(value interface{}, priority int) {
   newNode := &Node{
      value:    value,
      priority: priority,
      next:     nil,
   }
	
   if pq.head == nil || newNode.priority > pq.head.priority {
      newNode.next = pq.head
      pq.head = newNode
   } else {		
      curr := pq.head
      for curr.next != nil && newNode.priority <= curr.next.priority {
         curr = curr.next
      }
      newNode.next = curr.next
      curr.next = newNode
   }
}

func main() {
	
   pq := &PriorityQueue{
      head: nil,
   }	
   
   pq.Insert("Apple", 2)
   pq.Insert("Banana", 1)
   pq.Insert("Orange", 3)
	
   curr := pq.head
   for curr != nil {
      fmt.Println("Value:", curr.value, "Priority:", curr.priority)
      curr = curr.next
   }
}

Output

Value: Orange Priority: 3
Value: Apple Priority: 2
Value: Banana Priority: 1

Example 4

In this example, we define the Remove method for the PriorityQueue struct. The method removes the node with the highest priority from the priority queue and returns its value.In the main function, we create a sample PriorityQueue instance and insert three nodes with different values and priorities. We then call the Remove method twice and store the returned values in variables removed1 and removed2. Finally, we print the values of the removed nodes to verify the removal operation.

package main

import "fmt"

type Node struct {
   value    interface{}
   priority int
   next     *Node
}

type PriorityQueue struct {
   head *Node
}

func (pq *PriorityQueue) Insert(value interface{}, priority int) {
}

func (pq *PriorityQueue) Remove() interface{} {
   if pq.head == nil {
      return nil
   }

   removedValue := pq.head.value
   pq.head = pq.head.next

   return removedValue
}

func main() {
   pq := &PriorityQueue{
      head: nil,
   }

   pq.Insert("Apple", 2)
   pq.Insert("Banana", 1)
   pq.Insert("Orange", 3)

   removed1 := pq.Remove()
   removed2 := pq.Remove()

   fmt.Println("Removed value 1:", removed1)
   fmt.Println("Removed value 2:", removed2)
}

Output

Removed value 1: <nil>
Removed value 2: <nil>

Conclusion

In Conclusion, the Golang program successfully implements a priority queue using a linked list. The priority queue allows for efficient insertion of elements based on their priority and retrieval of the highest priority element. The program utilizes a Node struct to represent each element in the queue, and a PriorityQueue struct to manage the queue operations.The implementation provides methods to insert elements into the queue, remove the highest priority element, check if the queue is empty, retrieve the size of the queue, and peek at the highest priority element without removing it.

Updated on: 20-Jul-2023

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements