Q3(a) 15 points] Consider a class MyListImplementation that keeps a doubly linke
ID: 3600868 • Letter: Q
Question
Q3(a) 15 points] Consider a class MyListImplementation that keeps a doubly linked list with header and trailer sentinel nodes (referenced by instance variables of the list implementation called header and trailer). Assume that the Node class has the usual getter and setter methods. Write the sequence of Java statements that would be used within MyListImplementation, in order to insert the Node n at the front of the list. [You can use assignments to instance variables and you can call methods of the Node class, but do not call methods of the List ADT itself.] Q3(b) [5 points] A Comparator object is used in data structures, to allow the user to control the order placed on different objects by the structure. Give instructions that teach someone how to define a Comparator. In particular, you need to indicate any methods that the Comparator must haveExplanation / Answer
If you post more than 1 question, as per chegg guidelines I have to answer only 1.
// assuming structure of node is
class Node
{
int data;
Node next;
Node prev;
// constructor
Node(int data)
{
this.data = data;
next = null;
prev = null;
}
// getter methods
int getData()
{
return data;
}
Node getNext()
{
return next;
}
Node getPrevious()
{
return prev;
}
// setter methods
void setData(int data)
{
this.data = data;
}
void setNext(Node next)
{
this.next = next;
}
void setPrevious(Node prev)
{
this.prev = prev;
}
}
public class MyListImplementation
{
// point to header of the list
public Node header;
// point to the end of the list
public Node trailer;
public void addElement(Node n)
{
// create a new node with value same as of node n
Node new_node = new Node(n.getData());
// make the next pointer of new node
// to point at the header node
new_node.setNext(header);
// if the list is not empty
if(header != null)
// make the prev pointer of the previous header node
// to point at the new node
header.setPrevious(new_node);
// make new node the new header node
header = new_node;
// if list was previously empty
if(trailer == null)
// make trailer to point to new node
trailer = new_node;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.