Member Avatar for Gsterminator

I need help with an add boolean method in a singly linked list, The only difference is that i start off with a dummy head. The method's job is to add non-repeating objects to the linked list. Please help:

public boolean add(Object newData){
      Node current = head.getNext();
      Node v = new Node(newData, null);
      tail = v;
      if(current == null){//list is empty
          head.setNext(v);
          return true;
      }
      else{
          while(current!= null){
              if(newData != current.getElement()){
                  current = current.getNext();
                  current.setNext(v);
              }
              else return false;
          }
      }
      return true;

Recommended Answers

All 3 Replies

I do have some questions here.
first of all, why do you initialize v before you know if you'll need it or not? in case you don't need it, you're just occupying memory and resources for something you don't need.
but, here:

while(current!= null){
if(newData != current.getElement()){
current = current.getNext();
current.setNext(v);
}
else return false;
}

you only reach this code when current != null so, unless you actually get into the situation where current == newData (which, btw is NOT the right way to compare objects for equality, you should use the equals method), you're entering an endless loop.

but the next line really makes me wonder:
current = current.getNext();
do you have a node containing node's, or is there an error here?

Member Avatar for Gsterminator

So the v is initialized because i'm trying to store the new object into a new Node. So that way when i reach the end of the list i can replace null in the last node to setNext(v). I do enter an infinite loop.

Also the current = current.getNext(); assigns the current node to the next one.

Member Avatar for Gsterminator

here is my node class:

public class Node {
  private Object element; // we assume elements are character strings
  private Node next;
  /** Creates a node with the given element and next node. */
  public Node(Object s, Node n) {
    element = s;
    next = n;
  }
  public void addNodeAfter(Object newElem){
      next = new Node(newElem, next);
  }
  /** Returns the element of this node. */
  public Object getElement() { return element; }
  /** Returns the next node of this node. */
  public Node getNext() { return next; }
  // Modifier methods:
  /** Sets the element of this node. */
  public void setElement(Object newElem) { element = newElem; }
  /** Sets the next node of this node. */
  public void setNext(Node newNext) { next = newNext; }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.