Results 1 to 2 of 2
  1. #1
    cris9288 is offline Member
    Join Date
    Dec 2011
    Rep Power

    Default find method in doubly linked list


    I am trying to write a find method that iterates through a doubly linked list from the beginning and end until either one of the iterators runs in to the object being searched for or until the two iterators meet. However, I am having trouble getting it to work properly. I am able to get a successful search, but in the case where the object is not found I am getting a null-pointer exception. My code is as follows:

    Java Code:
             DoubleLinkNode<AnyType> p =;
             DoubleLinkNode<AnyType> j = tail.previous;
             while(p != j && !p.element.equals(item) && !j.element.equals(item)){
                 p =;
                 j = j.previous;
             if (p == j)
                 return null;
             else if (p.element.equals(item))
                 return new LinkedListIterator<>(p);
                 return new LinkedListIterator<>(j);
    if I search for an item not in the list I get an exception at the line with the while statement. Is it not correct to say that the loop should continue as long as p does not reference the same node as j? Thanks for your help.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Voorschoten, the Netherlands
    Blog Entries
    Rep Power

    Default Re: find method in doubly linked list

    Are 'head' and/or 'tail' elements of your list? If so, don't start with and tail.previous; (you're not checking the first and last elements and for a list with less than three elements your algorithm goes kaboom!) Also, suppose p and j point to adjacent nodes; advancing bother p and j makes them pass each other and your algorithm also goes kaboom!

    kind regards,

    Build a wall around Donald Trump; I'll pay for it.

Similar Threads

  1. find the sum of two Doubly Linked Lists
    By MaceMan in forum New To Java
    Replies: 7
    Last Post: 11-04-2011, 02:17 AM
  2. Doubly-Linked list
    By swp in forum New To Java
    Replies: 3
    Last Post: 10-11-2011, 03:27 PM
  3. Replies: 12
    Last Post: 10-10-2010, 11:17 PM
  4. Doubly Linked List
    By matin1234 in forum New To Java
    Replies: 0
    Last Post: 06-02-2010, 05:58 AM
  5. Help with Doubly linked list
    By Dr Gonzo in forum New To Java
    Replies: 5
    Last Post: 12-06-2008, 07:45 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts