user18174
user18174

Reputation: 25

How to add an element to a linked list?

So a method for part of a project requires that I check to see that an E element is already in the node list. If not, then I add the element to the list and return true (as the method is type boolean). However, I keep getting an error in my JUnit test class. So I wanted to know what is wrong with my code currently. Here is the method:

public boolean add(E element) 
{
    for(Node ref = first; ref != null; ref = ref.next)
    {
        first  = new Node(element);

        if(!(element.equals(ref.data)))
        {
            n++;
            add(element);
            return true;
        }
        else if(element.equals(ref.data))
        {
            return false;
        }
    }
return false;
}

I'm pretty sure that the way I formatted the code is wrong. I'm not really familiar with nodes as I am with arrays so that is the reason why the code may be a disgrace. And btw, n is for size.

Upvotes: 0

Views: 76

Answers (2)

akhil_mittal
akhil_mittal

Reputation: 24157

The logic should have two parts:

  1. First check in the complete list if the element exists or not? If it does return false and dont do anything else go to step 2.
  2. If element does not exist then insert it and return true.

This is shown in the following code:

public boolean add(E element) 
{
    boolean doesElementExist = false;
    //Step 1
    for(Node ref = first; ref != null; ref = ref.next)
    {
        if(element.equals(ref.data))
        {
            doesElementExist =  false;
            break;
        }
    }
    //Step 2
    if(!doesElementExist) {
      // Now we need to add element.
      Node newNode = new Node(element);
      newNode.next = first;
      first = newNode;
      doesElementExist = true;
    }
    return doesElementExist;
}

Upvotes: 0

Derek T. Jones
Derek T. Jones

Reputation: 1822

Your method appears to be combining both a recursive approach and an iterative approach to search, and in neither case do you handle the actual adding of the new element to the list.

You didn't specify where the new element should be added (front or back), so I'll assume front. I'm also assuming that first in your code is a field of your class, because it isn't otherwise declared.

A recursive solution doesn't make much sense here and doesn't have any advantages that I can see in this case. So here's one iterative solution, which puts the new element in front if not found:

public boolean add(E element) 
{
    for (Node ref = first; ref != null; ref = ref.next)
    {
        if (element.equals(ref.data)) {
            return false;
        }
    }
    Node newFirst = new Node(element);
    newFirst.next = first;
    first = newFirst;
    return true;
}

Upvotes: 1

Related Questions