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.
निम्नलिखित में से कौन सा वाक्य शुद्ध है ?
मुझे बहुत ही मीठा खाना पसंद करती हूँ।
निम्न लिखित प्रत्येक प्रश्न को चार भागों में बांटा गय�...
निम्नलिखित प्रत्येक प्रश्न में दिये गये चार - चार विकल्पो...
निम्नलिखित प्रत्येक प्रश्न को चार भागों में बाँटा गया है�...
निम्नलिखित वाक्य में कुछ अक्षर/शब्द मोटे अक्षरों में दर्�...
निम्नलिखित में से शुद्ध वर्तनी वाला शब्द चुनिए।
निम्नलिखित प्रश्न में , चार विकल्पों में से , उस विकल्प का च...
निम्नलिखित वाक्य में कुछ अक्षर/शब्द मोटे अक्षरों में दर्�...
गोलियों की (1)/ बौछार (2)/ कोई न(3)/ सका(4)/ टिक(5)/ के सामने (6)