For this problem, there is a complete linked list program which supports the fol
ID: 3709578 • Letter: F
Question
For this problem, there is a complete linked list program which supports the following commands from the user: insert, display, delete, average, find, insertBefore, insertAfter. insert allows them to insert a number into the current list, display will display the numbers in the current list etc. The program is complete except the body for delete has been removed. Given the following class for the nodes in a linked list: public class Node { ... public void putNext(Node n) {...} // change next field to n 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 x in the linked list and delete it. For example, delete(4) would return something like "deleted 4" or "Not found". Your statements will be inserted inside a method like the following: public String delete(int x) { // 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 delete(int x)
{
// 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
// if the list is empty
if( head == null )
return "Not found";
// if head is to be removed
if( head.getData() == x )
{
// make second node the new head
head = head.getNext();
return "deleted " + String.valueOf( x );
}
// point trav to the head of the list
Node trav = head;
// traverse through the list
while( trav.getNext() != null )
{
// if the next node is the node to be deleted
if( trav.getNext().getData() == x )
{
// remove the node
trav.putNext( trav.getNext().getNext() );
return "deleted " + String.valueOf( x );
}
// go to next node
trav = trav.getNext();
}
// if the node x is not present in the list
return "Not found";
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.