Reverse a Singly Linked List
Problem statement
You are given the head of a singly linked list. Reverse the list so that its last node becomes the first and every link points the other way, and return the new head.
If the list is empty, return an empty list.
Function
reverseLinkedList(head: ListNode) → ListNodeExamples
Example 1
head = [3,8,1]return = [1,8,3]The links are turned around: the old tail 1 becomes the new head, and the old head 3 becomes the new tail.
Example 2
head = [-7,0,7,0]return = [0,7,0,-7]Read from the end, the values are 0, 7, 0, -7. Equal values (the two zeros) are still separate nodes, and each one is kept.
Example 3
head = [6,-2]return = [-2,6]With two nodes, the second node now points to the first, and the first points to nothing.
Constraints
- The list has between
0and500nodes. -1000 <= node.val <= 1000