The linked implementation of a queue has two data fields. The field firstNode re
ID: 3578383 • Letter: T
Question
The linked implementation of a queue has two data fields. The field firstNode references the queue's front element; lastNode references the element at the back of the queue. Consider the following method where the object item is of the generic type T; isEmpty () is a method that returns true if the queue is empty; setNextNode (newNode) is a setter method of the private class Node of the linked implementation of a queue, which sets a value to the data field next of the node. public void xxxxxx(T item){Node newNode = new Node(item, null); if (isEmpty()) firstNode = newNode; else lastNode.setNextNode(newNode); lastNode - newNode;} What does the method xxxxxx do? Suggest a self-explaining name for the method.Explanation / Answer
sleft-explanatory name of the method xxxx would be 'Enqueue'
public void Enqueue(T item)
{}
Explanation for the working of the method:
linewise explanation
1) public void Enqueue(T item)
Its the definition of the method
2)Node newNode = new Node(item,null); // null is the address parameter whcich stores the address of next consecutive element.
This statement creates a new node object of type Node by calling constructor of class Node.
There has to be Node class defined in the program which has its own variable and constructor.
Here we are creating a new node of the queue by creating object of type classs Node
Its like variable declaration, because object is the user defined variable of type class.
3)if(isEmpty())
here we are calling isEmpty function which checkes whether we have any previous node available for queue
or its the first time we are creating the queue.
4)fisrtNode = newNode;
Here firstNode is like a pointer node which keeps track of the Front also called as Head of the queue from which end
deletion of elements take place.
5)else
lastNode.setNextNode(newNode);
if we are not initiating queue , i.e. if we have some elements available in the queue this statement will invoke.
It assigns a new node at after the current Last Node pointed by lastNode pointer.
6) lastNode = newNode;
finally lastNode pointer update with the recently added node.
lastNode is a poiner which keeps track of REAR also called as Tail end from which insertion of element takes place.
general info about queue data structure:
Queue if FIFO(first in first out) data structure
insertion happens at REAR(tail) end
deletion happens at FRONT(head) end
If any more explanation/help require, post in comments section
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.