Reverse a singly linked list.
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
A linked list can be reversed either iteratively or recursively. Could you implement both?
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let newList = null;
let cur = head;
let tempNext = null;
while(cur!==null){
tempNext = cur.next;
cur.next = newList;
newList = cur;
cur = tempNext;
}
return newList;
};