Lucky
Lucky

Reputation: 335

Object.keys in reverse order

I have interesting task. I solved the half of it but can't to find the solution to solve the rest. Hope someone can point me to the right direction.

I found the solution close to mine task. But mine is slightly different and use ES6.

There is nested object.

let someList = {

   value: 1,

   next: {

      value: 2,

      next: {

         value: 3,

         next: {

            value: 4,

            next: null

            }

         }

    }

};

I received all values.

function reversePrint(linkedList) {

Object.keys(linkedList).map(key => {
let myKey = linkedList[key];
typeof myKey == "object" ?  console.log(reversePrint(myKey)) : console.log(myKey);
});

}

reversePrint(someList);

But the problem is: how i can get all values in reverse order?

Fiddle: https://jsfiddle.net/L83puqbz/17/

I tried use reduce for to make array and reverse it but every value was in separate array.

Fiddle https://jsfiddle.net/L83puqbz/20/

Any help will be greatly appriciated.

Upvotes: 0

Views: 1411

Answers (2)

iaretiga
iaretiga

Reputation: 5215

As others have suggested, you can do this with recursion.

function reverse(node) {
    return (node.next === null) ? [node.value] : [...reverse(node.next), node.value];
}

Or, you can use a simple loop:

function reversedValues(node) {
    const values = [];
    while (node !== null) {
        values.unshift(node.value);
        node = node.next;
    }
    return values;
}

Advantage of first solution is simplicity and elegance. Disadvantage is that it can lead to a stack overflow if your linked list is really huge. Second solution is a bit more clunky and verbose, but it's not prone to stack overflow.

Upvotes: 3

curtainrising
curtainrising

Reputation: 249

EDIT - sorry yes, more explanation.

The following code will go through the linked list and print the values in reverse order.

Since the log is after the recursive call, this will go all the way to the last node before the console logs start. Then after each console log, the current function in the stack will end, allowing the previous function to continue to it's print.

let someList = {
  value: 1,
  next: {
    value: 2,
    next: {
      value: 3,
      next: {
        value: 4,
        next: null
      }
    }
  }
};

function printAfter(node){
  if(node.next != null){
    printAfter(node.next);
  }
  console.log(node.value);
}

printAfter(someList)

Upvotes: 5

Related Questions