Mahmoud_Hawara

Priority Queue using linked list

Nov 15th, 2022 (edited)
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. public class Solver
  2. {
  3.     public static void main(String args[])
  4.     {
  5.  
  6.     }
  7. }
  8.  
  9. class Node
  10. {
  11.     int data;
  12.     Node next;
  13.  
  14.     public Node(int d)
  15.     {
  16.         data = d;
  17.     }
  18. }
  19.  
  20. class pQueue    // the smallest element is the highest priority
  21. {
  22.     Node front;
  23.  
  24.     public void push(int d)
  25.     {
  26.         Node temp = new Node(d);
  27.  
  28.         if (isEmpty() || d <= front.data)
  29.         {
  30.             temp.next = front;
  31.             front = temp;
  32.             return;
  33.         }
  34.  
  35.         Node prev = front, curr = front.next;
  36.  
  37.         while (curr != null)
  38.         {
  39.             if (d <= curr.data)break;
  40.             prev = curr;
  41.             curr = curr.next;
  42.         }
  43.         temp.next = prev.next;
  44.         prev.next = temp;
  45.        
  46.         return;
  47.     }
  48.    
  49.     public Node pop()
  50.     {
  51.         if (isEmpty())
  52.         {
  53.             System.out.println("Can't Pop, The Queue is Empty");
  54.             return null;
  55.         }
  56.         Node temp = front;
  57.         front = front.next;
  58.         return temp;
  59.     }
  60.  
  61.     public Node peek()
  62.     {
  63.         if (isEmpty())
  64.         {
  65.             System.out.println("The Queue is Empty");
  66.         }
  67.         return front;
  68.     }
  69.  
  70.     public void clear()
  71.     {
  72.         while (isEmpty() == false)
  73.         {
  74.             pop();
  75.         }
  76.         System.out.println("Done");
  77.         return;
  78.     }
  79.  
  80.     public void display()
  81.     {
  82.         if (isEmpty())
  83.         {
  84.             System.out.print("The Queue is Empty");
  85.         }
  86.         Node curr = front;
  87.         while (curr != null)
  88.         {
  89.             System.out.print(curr.data + " ");
  90.             curr = curr.next;
  91.         }
  92.         System.out.println();
  93.         return;
  94.     }
  95.    
  96.     public boolean isEmpty()
  97.     {
  98.         return front == null;
  99.     }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment