JAVA Add the following method to LinkedList.java.Method public void addAsSecondN
ID: 3736026 • Letter: J
Question
JAVA Add the following method to LinkedList.java.Method public void addAsSecondNode(String d)that will add a new Node to the linked list with String d as the second node in the list. If the list is empty, it will add it as the first node.
/class Node public class Nod private String data;private Node next;public Kode String d, Node n)i data d; next = n ; public String getata) return data; public Node getiexti) return nexti public void Data LS tring d)( data = d;} public void etiext node n){ next = n; } public string return data> sostting(){ /class tinkedtist (only the first few methods are given here) public class tinkedtists private Node front; private jnt count; //constructor public Tinkedtist) front - null; count 0; /fadd a node to the front of the linked list public void addRoErontistring d)i Node n; n# new Nodeld, front): front -n;count++; //get the current size of the list public int sizet)i return count; h //check if the list is empty public baaleandAR nRARL) { return (count 0); } /clear the 1ist public void glearf)( front null; count-o; } //get the content of the first node public String getErontlatai) 1 if (front--null) return Empty list else return //new method added - get the first node public Node getRrRD) i return front; //scan the list and print contents public void eniimeratei) i Kode cu = front; while (surxenull) i Curx)Explanation / Answer
As you attached as image It is difficult to write and get the above code well the below example tell you the same thing what you want to achive, please refer that
public class SinglyLinkedList {
…
public void addLast(SinglyLinkedListNode newNode) {
if (newNode == null)
return;
else {
newNode.next = null;
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
}
public void addFirst(SinglyLinkedListNode newNode) {
if (newNode == null)
return;
else {
if (head == null) {
newNode.next = null;
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head = newNode;
}
}
}
public void insertAfter(SinglyLinkedListNode previous,
SinglyLinkedListNode newNode) {
if (newNode == null)
return;
else {
if (previous == null)
addFirst(newNode);
else if (previous == tail)
addLast(newNode);
else {
SinglyLinkedListNode next = previous.next;
previous.next = newNode;
newNode.next = next;
}
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.