user2770982
user2770982

Reputation: 33

Displaying all nodes in Linked List

This is part of Linked List class to display all nodes.

What this method is trying to do is set the front (yes, I am using front instead of head which doesn't matter but I'm implementing linked list based queue) to a pointer, in this case called "cur" and check if cur next node is not null, if it is not then get the element (two parts, share and price) and set the cur to the next node, rinse and repeat until it the next cur (before it steps into) is null, in that case it exits the loop and just print that last cur (before the null aka tail/rear). Add all elements to s (by concatenating)

public Object displayAll() {
        Node cur = front;
        Object s = null;
        while(cur.getNext() != null) {
             s += cur.getShare() + " @ " + cur.getPrice();
            cur.setNext(cur);
        }
        s += cur.getShare() + " @ " + cur.getPrice();
        return s;
}

Output: It repeats the first element countless times. Intended Output: I don't want the repetition but display all elements of all nodes.

What am I missing? Any pointers please?

Upvotes: 1

Views: 1564

Answers (2)

Narendra Pathai
Narendra Pathai

Reputation: 41935

while(cur.getNext() != null) {             
   s += cur.getShare() + " @ " + cur.getPrice();
   cur = cur.getNext();
}

I have assigned cur = cur.getNext() are you were not re-assigning cur to next node. Also I have removed cur.setNext(cur);

You were getting infinite loop because in the while condition you were checking that the next node should not be null but no where in the loop you were assigning the cur = next, so due to that you remain on the first node and loop infinitely.

Upvotes: 2

Ryan Stewart
Ryan Stewart

Reputation: 128779

cur.setNext(cur) looks pretty suspicious, like you're setting a node to link to itself, which is obviously an infinite relationship.

Upvotes: 1

Related Questions