Time complexity : O(n). Assume that nn is the list's length, the time complexity is O(n)O(n).
Space complexity : O(1).
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
let [prev, current] = [null, head];
while(current) {
[current.next, prev, current] = [prev, current, current.next];
}
return prev;
};