Chip594
Chip594

Reputation: 3

Java, Doubly-Link List: Is my logic wrong?

I'm having trouble with a homework assignment, moving through a doubly linked list using an iterator. The following is the method that seems to be the problem, but it seems logically correct to me. I have a runner file that I'm using to pass a list, the runner file prints out both forwards and backwards to see if my links are working correctly. If I add a item using the add(T element) method it works fine both forwards and backwards. However, if I add an item using the add(T element, int index) method the list will output correctly forwards but on the backwards iterator the newly added item isn't in the output.

which leaves me to suspect current.getNextNode().setPriorNode(newNode); is the problem but it seems like it would be correct to me, or am I wrong?

Thanks you!

UPDATE: I edited the code with the fix for incase anyone else has the same problem in the future.

public void add(T element) {

    Node<T> node = new Node(element);

    if (itsFirstNode == null) {
        itsFirstNode = node;
        itsLastNode = node;
    }
    else {
        itsLastNode.setNextNode(node);
        node.setPriorNode(itsLastNode);
        itsLastNode = node;
    }
    size++;
} // end of add() method

  public void add(T element, int index) {
    int counter = 0;
    Node<T> newNode = new Node(element);
    Node<T> current = itsFirstNode;
    while (current.getNextNode() != null ) {
        if (counter == index - 1 )
            break;
        current = current.getNextNode();
        counter++;
    }
    newNode.setNextNode(current.getNextNode());
    current.getNextNode().setPriorNode(newNode);

    newNode.setPriorNode(current);
    current.setNextNode(newNode);

    size++;
} // end of Overloaded add() method

Upvotes: 0

Views: 82

Answers (3)

Maruf Hossain
Maruf Hossain

Reputation: 39

You can use following code in last 5 line

newNode.setNextNode(current.getNextNode());
current.getNextNode().setPriorNode(newNode);

current.setNextNode(newNode);
newNode.setPriorNode(current);

size++;

Upvotes: 0

IEE1394
IEE1394

Reputation: 1261

instead of

current.getNextNode().setPriorNode(newNode);

try

newNode.getNextNode().setPriorNode(newNode);

Upvotes: 0

Deltharis
Deltharis

Reputation: 2373

newNode.setNextNode(current.getNextNode()); 
current.setNextNode(newNode);

newNode has next one set correctly, current has next one as newNode

newNode.setPriorNode(current);

newNode has prior set correctly

current.getNextNode().setPriorNode(newNode);

current.getNextNode() is newNode, so you set newNode as the prior of newNode. It should work if you move this line two lines earlier

Upvotes: 3

Related Questions