reverse singly linked list js 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 a linked list js
function LinkedListNode(value) {
this.value = value;
this.next = null;
}
let head = new LinkedListNode(10)
head.next = new LinkedListNode(25)
head.next.next = new LinkedListNode(46)
const reverse = (head) => {
if (!head || !head.next) {
return head;
}
let temp = reverse(head.next);
head.next.next = head;
head.next = undefined;
return temp;
}
head = reverse(head)