Knowee
Questions
Features
Study Tools

Implement a generic Queue data structure in Java using a linked list. The Queue should support the basic operations of enqueue, dequeue, peek, and check if the queue is empty.

Question

Implement a generic Queue data structure in Java using a linked list. The Queue should support the basic operations of enqueue, dequeue, peek, and check if the queue is empty.

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a simple implementation of a Queue data structure in Java using a linked list:

import java.util.LinkedList;

public class Queue<T> {
    private LinkedList<T> list = new LinkedList<T>();

    // Add element to end of queue
    public void enqueue(T item) {
        list.addLast(item);
    }

    // Remove element from front of queue
    public T dequeue() {
        if (list.isEmpty()) {
            return null;
        }
        return list.removeFirst();
    }

    // Get element from front of queue without removing it
    public T peek() {
        if (list.isEmpty()) {
            return null;
        }
        return list.getFirst();
    }

    // Check if the queue is empty
    public boolean isEmpty() {
        return list.isEmpty();
    }
}

In this code:

  • We use a LinkedList to store the elements of the queue. The end of the LinkedList represents the end of the queue and the start of the LinkedList represents the front of the queue.
  • The enqueue method adds an element to the end of the queue.
  • The dequeue method removes an element from the front of the queue and returns it. If the queue is empty, it returns null.
  • The peek method returns the element at the front of the queue without removing it. If the queue is empty, it returns null.
  • The isEmpty method checks if the queue is empty.

This problem has been solved

Similar Questions

Implement linked list version of Queue data structure. Define all operations that can be performed over a queue.

In linked list implementation of a queue, the important condition for a queue to be empty is?

Discuss array and linked list representation of queue datastructure

What data structure is a Double-ended queue (Deque) most similar to in terms of its functionality?a)Linked Listb)Priority Queuec)Queued)Stack

A queue is a ____________________ data structure. A. link based B. none of the above C. FIFO D. LIFO E. array based

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.