Reverse Linked List
EasyLinked List · NVIDIA
You are given head, the first node of a singly linked list. Reverse the list and return the head of the reversed list.
After reversing, the old last node becomes the head and the old head points to None. If the list is empty, return None.
Follow-up: the list can be reversed iteratively or recursively. Can you write both?
Example 1
- Input:
- head = [3,8,-1,6]
- Output:
- [6,-1,8,3]
- Explanation
- Every
nextpointer is flipped, so the old tail 6 becomes the new head and the old head 3 now points toNone.
Example 2
- Input:
- head = [2,2,3,2]
- Output:
- [2,3,2,2]
- Explanation
- Nodes are reversed by position, so the 3 moves from third place to second.
Example 3
- Input:
- head = []
- Output:
- []
- Explanation
- There are no nodes, so the reversed list is also empty (
None).
Constraints
- The number of nodes is in the range
[0, 5000] -5000 <= Node.val <= 5000