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.
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
enqueuemethod adds an element to the end of the queue. - The
dequeuemethod removes an element from the front of the queue and returns it. If the queue is empty, it returns null. - The
peekmethod returns the element at the front of the queue without removing it. If the queue is empty, it returns null. - The
isEmptymethod checks if the queue is empty.
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
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.