In this post, we will see Priority Queue in Java | Priority Queue Using Heap | Priority Queue Implementation in Java
Watch this video to know about Priority Queue in Java | Priority Queue Using Heap | Priority Queue Implementation in Java:
Watch on YouTube: https://www.youtube.com/watch?v=deTpicgkFEQ
Program Code: (PQueue.java)
import java.util.*; public class PQueue { public static void main(String args[]) { Queue q = new PriorityQueue(); int head; System.out.println("Queue: " + q); q.add(10); //offer() System.out.println("Queue: " + q); q.add(25); System.out.println("Queue: " + q); q.add(22); System.out.println("Queue: " + q); q.add(18); try{ System.out.println("Queue: " + q); head=(int)q.remove(); //poll() System.out.println("Queue: " + q); head=(int)q.remove(); System.out.println("Queue: " + q); head=(int)q.remove(); System.out.println("Queue: " + q); head=(int)q.remove(); System.out.println("Queue: " + q); head=(int)q.remove(); } catch(Exception e) { System.out.println("Queue is empty"); } } } |
Output:
parag@parag-Inspiron-N4010:~/Desktop/prog$ javac PQueue.java
Note: PQueue.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. parag@parag-Inspiron-N4010:~/Desktop/prog$ java PQueue Queue: [] Queue: [10] Queue: [10, 25] Queue: [10, 25, 22] Queue: [10, 18, 22, 25] Queue: [18, 25, 22] Queue: [22, 25] Queue: [25] Queue: [] Queue is empty |
Explanation:
1. Add 10
Queue: [10]
2. Add 25
Queue: [10, 25]
3. Add 22
Queue: [10, 25, 22]
4. Add 18
5. Remove next (head) element
Queue: [18, 25, 22]
6. Remove next (head) element
Queue: [22, 25]
7. Remove next (head) element
Queue: [25]
8. Remove next (head) element
Queue: [ ]
No comments:
Post a Comment