简体   繁体   中英

get element from an index in a linked list

I'm writing my own LinkedList class (i know there is one in the API .. etc) I have integers stored in my DLink and getElement() returns the integer stored in the link.

I am getting a null pointer exception from the line "return temp.getElement();" is there something wrong with my get method? eg of why I want this method: when I call get(0) I want to return the first element in the list

public int get(int index)
{

       //forces the index to be valid
      assert (index >= 0 && index < size());

      DLink temp = _firstLink; //start at the head of the list

      //iterate to the correct node
      for(int i = 0; i < index; i++)
      {
          temp = temp._next;
      }

      return temp.getElement(); //and return the corresponding element



    }

here is my DLink class if you want to look at it:

//elements in DLink are integers
public class DLink {
    public int _element;

    public DLink _next;
    public DLink _previous;

    public DLink(int e)
    {
        _next = null;
        _previous = null;

        this._element = e;
    }

    public int getElement()
    {
        return _element;
    }

    public void setNext(DLink link)
    {
        _next = link;
    }
    public void setPrev(DLink link)
    {
        _previous = link;
    }

    public DLink getPrev()
    {
        return _previous;
    }

    public DLink getNext()
    {
        return _next;
    }

}

When do you initialize your list? Or to be more specific - where is _firstLink being declared and assigned? What is the call you're making before getting the null pointer exception?

Without seeing the context - my guess is that you are not initializing _firstLink correctly.

I would suggest that you'll simply debug this code and review the data structure you defined in runtime.

If you are getting a null pointer exception, in this case there are two plausible explanation.

  1. your list is empty, ie there is no firstLink to begin with, and you get a null pointer because you are trying to access a pointer that is yet to be initialized.

  2. your list has only one element. Hence the firstLink.next() would give you a null pointer.

You should always implement a few checks before entering a while loop that iterates through a list.

if(firstLink == null)
    return;

if(firstLink.next() == null)
    return;

or you could have an initial clause before the while-loop

if(firstLink != null && firstLink.next() != null)
    while(true)
        ...do-something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM