Link List Travel

B

Bharat Bhushan

Hi,

I have a link list which I am attempting to print using the following loop.

LinkList tmp = Head;
while((tmp.Next != null)){
print("Nodes Number: "+tmp.Index);
}

Now the problem is that with this loop, I am missing the last node. Apart
from having the print("Nodes Number: "+tmp.Index); statement after the loop,
I can't get it to print the last node from the loop itself.


Any pointers??


Regards,

- Bharat.
 
N

Nate

The "last node" should always be NULL, and I assume you don't care to
have that printed. What you really mean (or should mean) is that the
second to last node isn't printing. My guess, and this is only a
guess, is that you don't have the last node set to NULL. If this isn't
the case, we'll deal with that later. Let me know if that was the
problem.
 
G

Gordon Beaton

LinkList tmp = Head;
while((tmp.Next != null)){
print("Nodes Number: "+tmp.Index);
}

Now the problem is that with this loop, I am missing the last node.
Apart from having the print("Nodes Number: "+tmp.Index); statement
after the loop, I can't get it to print the last node from the loop
itself.

Of course the next pointer in the last node will always be null, so
your loop will stop after the second to last node.

Make the loop condition "tmp != null" instead.

Then there's the small fact that you never actually step from one node
to the next, so the code you've posted will loop forever for any
non-empty list.

/gordon
 
B

Bharat Bhushan

Hi Gordon, Nate:

Many thanks for your replies.

I changed the condition to tmp != null and it gave me perfect result.


Thanks,

- Bharat.
 
N

Neomorph

Hi Gordon, Nate:

Many thanks for your replies.

I changed the condition to tmp != null and it gave me perfect result.

You can use:
for(LinkedList tmp = Head;tmp;tmp = tmp.Next)
print("Nodes Number: "+tmp.Index);

Just because you're not using numbers, doesn't mean you can't use the for()
loop ;-)
Thanks,

- Bharat.

Cheers.
 
G

Gordon Beaton

You can use:
for(LinkedList tmp = Head;tmp;tmp = tmp.Next)
print("Nodes Number: "+tmp.Index);

Just because you're not using numbers, doesn't mean you can't use
the for() loop ;-)

Java is not C!

Whatever style of loop you choose, the condition needs to be a boolean
expression:

for (LinkedList tmp = Head; tmp != null; tmp = tmp.Next) ...

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top