Given the head of a singly linked list, reverse the list and return the reversed list.
Example 1
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
The number of nodes is in the range [0, 5000].-5000 <= Node.val <= 5000Use three pointers: prev, curr, next.
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next; // save next
curr.next = prev; // reverse pointer
prev = curr; // advance prev
curr = next; // advance curr
}
return prev; // prev is the new head
}Time: O(n) · Space: O(1)