reverse a list in javascript code example
Example 1: reverse a linked list javascript
function reverse(head) {
if (!head || !head.next) {
return head;
}
let tmp = reverse(head.next);
head.next.next = head;
head.next = undefined;
return tmp;
}
Example 2: reverse array javascript
function reverseArray (arr){
if (arr.length === 0){
return []
}
return [arr.pop()].concat(reverseArray(arr))
}
console.log(reverseArray([1, 2, 3, 4, 5]))
Example 3: reverse an array javascript
const reversed = array1.reverseconst reversed = array1.reverse();
console.log('reversed:', reversed);
console.log('reversed:', reversed);
console.log('reversed:', reversed);