WikiGalaxy

Personalize

Peek Operation in Queue

Introduction to Peek Operation:

The peek operation in a queue allows us to view the front element of the queue without removing it. This operation is useful for checking the next element to be processed.

Queue Structure:


        // Visual representation of a queue
        [Front] -> [Data1] -> [Data2] -> [Data3] -> [Rear]
      

Step-by-Step Diagram:


        Step 1: Queue contains elements
        [Front] -> [10] -> [20] -> [30] -> [Rear]

        Step 2: Perform peek operation
        Peek element: 10
        Queue remains unchanged
        [Front] -> [10] -> [20] -> [30] -> [Rear]
      

Java Code Example:


        import java.util.LinkedList;
        import java.util.Queue;

        public class QueuePeekExample {
          public static void main(String[] args) {
            Queue queue = new LinkedList<>();
            queue.add(10);
            queue.add(20);
            queue.add(30);

            // Peek operation
            int peekElement = queue.peek();
            System.out.println("Peek element: " + peekElement);
          }
        }
      

Explanation of Code:

In this example, we create a queue and add three integers to it. The peek operation retrieves the front element of the queue, which is 10, without removing it. The queue remains unchanged after the operation.

Console Output:

Peek element: 10

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025