Question: Deleting a value in a linked list----- Code seems to be off a little. I don't know where the problem is. Given the following class

Deleting a value in a linked list----- Code seems to be off a little. I don't know where the problem is.

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 }
public String delete(int x) { if(head == null) { return "Not found"; } else if(head.getData() == x) { head = head.getNext(); return "deleted " + x; } else { Node temp = head; while (head.getNext() != null) { if(head.getNext().getData() == x) { head.putNext(head.getNext().getNext()); return "deleted " + x; } head = head.getNext(); } } return "Not found"; }

.Deleting a value in a linked list----- Code seems to be off

Program compiled and ran but the console output differs from the key. See belou: Console output expected. Max 5e lines-- Console output found. Max 50 lines- Linked list code sample. Options are: (insert, display, delete, average, find, insertBefore, insertAfter) (insert, display, delete, average, find, insertBefore, insertAfter) What would you like: inserted 2 What would you like: inserted 3 What would you like: Not found What would you like: deleted 3 hat would you like: deleted 2 What would you like: Not found What would you like: Bye Linked 1ist code sample. Options are: What would you like: inserted 2 What would you like: inserted 3 What would you like: Not found what would you like: Not found What would you like: deleted 2 What would you like Not found What would you like: Bye Console input data used (max 5 1ines) insert 2 insert 3 delete 4 delete 3 delete 2 delete 3 Exit Score for this question is e 2 You still have 6 chance(s) left

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!