The program is complete except the body of the method for insertBefore has been
ID: 3707885 • Letter: T
Question
The program is complete except the body of the method for insertBefore has been removed.
Given the following class for the nodes in a linked list: public class Node { ... Node (int x, Node n) {...} // constructor for creating nodes with data i.e. x and next i.e. n field values public void putNext(Node n) // for updating the next (pointer) field in the node public Node getNext() {...} // return next field public int getData() {...} // returns data } Assuming that the variable head points to (i.e. contains the address of) the first node of a linked list, write the statements to find the first occurrence of the data value m in the linked list and insert n before it. For example, insertBefore (4, 3) would find the first occurrence of 4 and insert 3 before it, then return "insert before 4 3 done", Or "4 not Found" if 4 is not in the list. Your statements will be inserted inside a method like the following: public String insertBefore (int m, int n) { // Whatever statements you provide in response to this question will // be inserted here BY THE SYSTEM and then compiled and tested as part of // a larger program which does many other things with the linked list }
Explanation / Answer
public String insertBefore (int m, int n) { if(head == null) { return m + " not found"; } else if(head.getData() == m) { head = new Node(n, head); return "insert before " + m + " " + n + " done"; } else { Node temp = head; while (temp.getNext() != null) { if(temp.getNext().getData() == m) { temp.putNext(new Node(n, temp.getNext())); return "insert before " + m + " " + n + " done"; } } } return m + " not found"; }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.