back to the lesson

## Output a single-linked list in the reverse order

importance: 5

Make two solutions: using a loop and using a recursion.

#### Using a recursion

The recursive logic is a little bit tricky here.

We need to first output the rest of the list and then output the current one:

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

function printReverseList(list) {

if (list.next) {
printReverseList(list.next);
}

}

printReverseList(list);``````

#### Using a loop

The loop variant is also a little bit more complicated then the direct output.

There is no way to get the last value in our `list`. We also can’t “go back”.

So what we can do is to first go through the items in the direct order and remember them in an array, and then output what we remembered in the reverse order:

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

function printReverseList(list) {
let arr = [];
let tmp = list;

while (tmp) {
arr.push(tmp.value);
tmp = tmp.next;
}

for (let i = arr.length - 1; i >= 0; i--) {