Shah
Shah

Reputation: 73

Recursive implementation of "append if not present" for linked list

public bool add(int e)
    {
        if(head == null)
        {
            Node n = new Node 
            {
                element = e
            };
            head = n;
            return true;
        }
        Node t = head;
        if(t.next == null)
        {
            if(t.element == e)
            { return false; }
            Node n = new Node
            {
                element = e
            };
            t.next = n;
            return true;
        }
        t = t.next;
        this.add(e);

        return true;
    }

This is a code to add a new node in set. No duplicated values allowed. There is Main Class called Sets and one inner class called Nodes. I know Node t = head; is creating a problem is there anyway to make this recursive? Even passing extra optional parameters doesn't help.

Upvotes: 0

Views: 144

Answers (1)

Pandacoder
Pandacoder

Reputation: 708

If I understood your question correctly, to make it recursive you would need to split it into two functions, a public one for handling the head == null case, and a private one for handling n.next == null and is recursive.

public bool add(int e)
{
    if (head == null)
    {
        head = new Node { element = e };
        return true;
    }

    return add(head, e);
}

private bool add(Node n, int e) {
    if (n.element == e)
        return false;

    if (n.next == null) {
        n.next = new Node { element = e };
        return true;
    }

    return add(n.next, e);
}

However, I would suggest instead doing something akin to the following which does everything in one function:

public bool add(int e)
{
    if (head == null)
    {
        head = new Node { element = e };
        return true;
    }

    if (head.element == e)
        return false;

    Node n = head;
    while (n.next != null) {
        if (n.element == e)
            return false;
        n = n.next;
    }

    n.next = new Node { element = e };
    return true;
}

Upvotes: 2

Related Questions