Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing a Javascript Linked list skips the last item

var someList = {
                   data : 1,
                   next : {
                              data : 2,
                                  next : {
                                             data : 3,
                                             next : {
                                                        data : 4,
                                                        next : null
                                                    }
                                         }
                          }
               };

var ar = []; 

function reversePrint( LList )
{
    var c = null;
    c = LList;

    while ( c.next != null )
    {
        ar.unshift( c.data );
        c = c.next;
    }

    console.log( ar );
}

This routine outputs data in array in reverse order.

The problem is : the loop doesn't get data : 4.

How do I rewrite it to output all of the data?

like image 462
DrStrangeLove Avatar asked Dec 09 '25 02:12

DrStrangeLove


1 Answers

for (var c = LList; c; c = c.next) {
    // do something with c.data
}
like image 149
ThiefMaster Avatar answered Dec 10 '25 14:12

ThiefMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!