Given the two classes below, the following code contains an error. Provide the c
ID: 3738431 • Letter: G
Question
Given the two classes below, the following code contains an error. Provide the correct implementation of the insertNodeAfterSpecificElement method.
Given the two classes below, the following code contains an error. Provide the correct implementation of the insertNodeAfterSpecificElement method.
class Node {
Node next;
Integer item;
public Node(Integer val) {
item = val;
next = null;
}
public Node(Integer val, Node n) {
item = val;
next = n;
}
}
public class LinkedList {
Node head;
public LinkedList(Integer val) {
head = new Node(val);
}
public void append(Integer val) {
Node tmpNode = head;
while (tmpNode.next != null) {
tmpNode = tmpNode.next;
}
tmpNode.next = new Node(val);
}
public void insertNodeAfterSpecificElement(Integer x, Integer y){
//if there are multiple node y, then add node x after first occurrence
Node current = head;
while(current!=null){
if(current.item.equals(y)){
Node n = new Node(x);
n.next = current.next;
current.next = n;
}else{
//If node y does not exist, add node x to end of linkedlist
if(current.next==null){
current.next = new Node(x);
}
}
current = current.next;
}
}
}
class Node {
Node next;
Integer item;
public Node(Integer val) {
item = val;
next = null;
}
public Node(Integer val, Node n) {
item = val;
next = n;
}
}
public class LinkedList {
Node head;
public LinkedList(Integer val) {
head = new Node(val);
}
public void append(Integer val) {
Node tmpNode = head;
while (tmpNode.next != null) {
tmpNode = tmpNode.next;
}
tmpNode.next = new Node(val);
}
public void insertNodeAfterSpecificElement(Integer x, Integer y){
//if there are multiple node y, then add node x after first occurrence
Node current = head;
while(current!=null){
if(current.item.equals(y)){
Node n = new Node(x);
n.next = current.next;
current.next = n;
}else{
//If node y does not exist, add node x to end of linkedlist
if(current.next==null){
current.next = new Node(x);
}
}
current = current.next;
}
}
}
Explanation / Answer
Please find my corrected code.
Please let me know in case of any issue.
Please rate my answer of if helped you!!
public void insertNodeAfterSpecificElement(Integer x, Integer y){
//if there are multiple node y, then add node x after first occurrence
Node current = head;
while(current!=null){
if(current.item.equals(y)){
Node n = new Node(x);
n.next = current.next;
current.next = n;
break;
}
current = current.next;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.