Question
Consider the following Java code snippet:
import java.util.PriorityQueue; public class HeapQuestion1 { public static void main(String[] args) { PriorityQueue minHeap = new PriorityQueue(); minHeap.add(10); minHeap.add(5); minHeap.add(20); minHeap.add(3); minHeap.add(15); System.out.println(minHeap.poll()); System.out.println(minHeap.peek()); System.out.println(minHeap.poll()); } } What will be the output of this program?Solution
A PriorityQueue in Java is by default a min-heap, meaning the smallest element has the highest priority. 1. minHeap.add(10); minHeap.add(5); minHeap.add(20); minHeap.add(3); minHeap.add(15); After these additions, the heap contains {3, 5, 10, 15, 20} (not necessarily in this order internally, but 3 is at the root). 2. System.out.println(minHeap.poll()); poll() removes and returns the smallest element. So, 3 is removed and printed. The heap now contains {5, 10, 15, 20}. 3. System.out.println(minHeap.peek()); peek() retrieves the smallest element *without removing it*. The smallest element is now 5. So, 5 is printed. The heap still contains {5, 10, 15, 20}. 4. System.out.println(minHeap.poll()); poll() removes and returns the smallest element again. So, 5 is removed and printed. The heap now contains {10, 15, 20}. Therefore, the output is 3, 5, 5.
निम्नलिखित प्रश्न में , दिए गए चार विकल्पों में से , उस विक�...
निम्ननलिखित प्रश्न में कौनसा विकल्प सही नहीं है ?
निम्नलिखित वाक्यों के रिक्त स्थान पर उसके नीचे दिए गए ...
निम्नलिखित शब्दों में से अतिकर का सही पर्याय है ?
"खेल खत्म, पैसा हजम" का अर्थ है:
निम्नलिखित में से ' विचित्र ' का पर्यायवाची क्या होगा ?
निम्नलिखित प्रत्येक प्रश्न में दिए गए शब्द के समानार�...
भारत सरकार ने हिन्दी को राजभाषा के रूप में कब स्वीकार �...
‘स्नेह’ शब्द का पर्यायवाची नहीं है:
मुहावरा “आँख दिखाना” का सही अर्थ है —