211k views
2 votes
Suppose we have a singly linked-list-based implementation of a Queue, built of Node elements that link to one another.

The Node class has a public Node next and a public E data instance variable.
The Queue has head and tail instance variables, pointing to the first and last Nodes of the list (or null if the list is empty), as well as an int size.
In other words, it is the implementation we wrote in lecture.
Write the void add(E e) method.

User Hrundik
by
7.9k points

1 Answer

4 votes

Final answer:

The add(E e) method adds an element to the end of the singly linked-list-based implementation of a Queue.

Step-by-step explanation:

The add(E e) method in the singly linked-list-based implementation of a Queue adds an element to the end of the queue. Here is an example implementation:

public void add(E e) {

Node newNode = new Node(e);

if (isEmpty()) {

head = newNode;

tail = newNode;

} else {

tail.next = newNode;

tail = newNode;

}

size++;

}

In this implementation, a new node is created with the given element. If the queue is empty, the head and tail both point to the new node. Otherwise, the tail's next pointer is set to the new node, and the tail is updated to point to the new node. Finally, the size of the queue is incremented.

User Ymi
by
7.4k points