Reverse single-linked list
by Alex Myronov
JavaScript
function Node(val) {
this.val = val
this.next = null
}
Node.prototype.add = function(val) {
this.next = new Node(val)
return this.next
}
const reverse = (head) => {
let reversed = null
let curr = head
while (curr) {
const temp = curr.next
curr.next = reversed
reversed = curr
curr = temp
}
return reversed
}
const head = new Node('1')
head.add('2')
.add('3')
.add('4')
.add('5')
console.log(reverse(head))