Reverse Linked List
Description
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution(javascript)
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
// const reverseList = (head) => {
// if (!head) {
// return head
// }
// let returned = { val: head.val, next: null }
// let current = head
// while (current.next) {
// current = current.next
// returned = {
// val: current.val,
// next: returned,
// }
// }
// return returned
// }
const reverseList = (head) => {
const aux = (current, acc) => {
if (!current) {
return acc
}
return aux(current.next, {
val: current.val,
next: acc,
})
}
return aux(head, null)
}