Let us consider a class LinkedList representing a linked list defined by its hea
ID: 3625807 • Letter: L
Question
Let us consider a class LinkedList representing a linked list defined by its head and tail.The implementation of LinkedList is based an inner class called Node . The code for LinkedList and Node is provided below.
Write a method that adds a new node at the FRONT of a linked list. This method must be implemented in LinkedList .
The signature of the method is:
public void addFirstNode(Object obj) where obj is the item of a Node .
public class LinkedList {
private class Node {
private Object item;
private Node next;
public Node(Object item) {
this.item = item;
}
public Node(Object item, Node next) {
this.item = item;
this.next = next;
}
public Object getItem() {
return item;
}
public void setItem(Object item) {
this.item = item;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
private Node head;
private Node tail;
public LinkedList(Node head, Node tail) {
this.head = head;
this.tail = tail;
}
public LinkedList() {
super();
}
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
public Node getTail() {
return tail;
}
public void setTail(Node tail) {
this.tail = tail;
}
...
}
Explanation / Answer
When inserting at the beginning of the linked list, you are replacing the head element. You need to create a new node containing the data the user is sending you, and then set the next pointer of this node to the previous head pointer. You should also check the data the user is sending to the method to make sure it is not null.
public void addFirstNode(Object obj) {
if (obj != null) {
Node newHead = new Node(obj, head); // Create a new node with the data the user is sending in
this.setHead(newHead); // Set the head of the list to the new node you just created
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.