
Problem
Solution
Submissions
Reverse a Linked List
Certification: Basic Level
Accuracy: 100%
Submissions: 2
Points: 10
Write a C# program to reverse a singly linked list. Given a pointer to the head node of a linked list, the task is to reverse the linked list.
Example 1
- Input: head = [1,2,3,4,5]
- Output: [5,4,3,2,1]
- Explanation:
- Step 1: Initialize three pointers: prev as null, current as head, and next as null.
- Step 2: Iterate through the list 1->2->3->4->5
- Step 3: For each node, save the next node, reverse the current node's pointer, move pointers one position ahead.
- Step 4: Return the new head of the reversed list, which is 5.
Example 2
- Input: head = [1,2]
- Output: [2,1]
- Explanation:
- Step 1: Initialize three pointers: prev as null, current as head, and next as null.
- Step 2: Iterate through the list 1->2
- Step 3: Save node 2 as next, point node 1 to null, move prev to node 1, move current to node 2.
- Step 4: Save null as next, point node 2 to node 1, move prev to node 2, current becomes null.
- Step 5: Return the new head of the reversed list, which is 2.
Constraints
- 0 ≤ Number of nodes ≤ 5000
- -5000 ≤ Node.val ≤ 5000
- Time Complexity: O(n) where n is the number of nodes in the list
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use three pointers to keep track of the current node and its previous and next nodes.
- Iterate through the list, changing each node's next pointer to point to the previous node.
- Return the new head of the reversed list.
- Be careful when handling edge cases like an empty list or a list with only one node.
- Consider both iterative and recursive approaches.