0

I need to remove a node from a linked list using recursion. this is the code that I have so far...

public class SortedSetNode implements Set {
    protected String value;
    protected SortedSetNode next;

public boolean remove(String element) {

    if (value.equals(element))
    {
        next = next.getNext();
        return true;
    }
    else
    {
        return next.remove(element);
    }
}

2 Answers 2

1

Well, without knowing what the problem is that you are facing, you would need a clause in there to check whether the item you are removing is actually in the linked list, i.e.

if(next == null){
    return false;
}

Other than that your code looks fine. What is the issue you are encountering?

Sign up to request clarification or add additional context in comments.

Comments

0

If the value attribute is the value of the current node, then you'll need to delete itself when value equals element, rather than delete the next. Unless it's the value of next node. You might need a start point, so when you compare value, you compare the next node's value with the string, and if found, do your next = next.getNext();. Of course a check of null is needed.

2 Comments

what if i changed it to this? if (next.value.equals(element))
Are you trying to write your own data structure from scratch or you want to implement java.util.Set interface? Anyway, have a look at those existing implementations will help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.