Reverse Linked List
You are given the head of a singly linked list. Reverse the list and return its new head.
Rewire the existing nodes by changing their next pointers; don't create new nodes. The tests read the list starting from the node you return.
Constraints
- The list has between
0and5000nodes. -5000 <= Node.val <= 5000
Examples
Example 1
Input: head = [1,2,3,4,5] Output: [5,4,3,2,1]
Every arrow is turned around, so 5 becomes the head and 1 the tail.
Example 2
Input: head = [1,2] Output: [2,1]
The two nodes swap places: 2 → 1.
Example 3
Input: head = [] Output: []
An empty list (head = null) stays empty: return null.
JavaScript you'll use: Linked list and tree nodes Destructuring, spread and rest
/**
* Linked list nodes are provided (you don't need to define them):
* class ListNode { constructor(val = 0, next = null) { this.val = val; this.next = next; } }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
function reverseList(head) {
}
Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.