recursion - Java - Deleting whole linked-list doesn't affect the actual list -


i typed recursive method delete nodes in simple linked-list in fact debugger shows method doesn't affect actual list , don't know why it's that. here's code:

class list { element root; ...}  class element {int value; element next; ...}   element delete(element head) {  if(head == null) return null;  head = delete(head.next);  return head; } 

there's nothing in delete method deletes anything, i.e. doesn't change list , doesn't change element in list. search through entire list find element .next() null, returns null.

you have change value somewhere.

so let's start delete(element) method. i've come understand, needs take element, head of list, , delete members of list. setting head = null won't work, @dan getz has noted. need able @ actual list, , have work element, element has know list contains it. , means need mylist field of type list in element. delete(element head) method do

head.mylist.deleteall(); 

that requires deleteall() method in list, set root = null;

or, if root accessible delete(element head) method, do

head.mylist.root = null; 

the point somehow have root, , passing in other method doesn't job.

old answer below, doesn't quite fit assignment requirements

start removing argument. don't need pass in head.

then, in body, set head = null (assuming have field called head).

return either null or previous value of head, whichever matches api.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -