DSA (Easy) —Linked List — Reverse Linked List (Python, Typescript & Go)
0 comments

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]
Example 2:

Input: head = [1,2]
Output: [2,1]
Example 3:
Input: head = []
Output: []
Constraints:
- The number of nodes in the list is the range [0, 5000].
- -5000 <= Node.val <= 5000
Explanation
Alright, imagine you have a train of toy cars, all linked together, and you want to reverse the order of the train.
Here’s how you’d do it in simple steps, like a recipe:
🚓Starting Point:
- You have a train of cars, with a “head” car at the front.
- You have an empty space called “previous car” (it’s empty at first).
🚓Take the head car:
- Grab the car at the front of the train. Let’s call it the “current car”.
🚓Remember the next car:
- Before you change anything, remember the car that’s linked to the “current car”. We’ll need it later. Let’s call this the “next car”.
🚓Unlink and Relink:
- Take the “current car” and unlink it from the rest of the train.
- Link the “current car” to the “previous car” space. (At first, this will link to nothing, but that’s okay!)
🚓Move the “previous car” marker:
- Now, the “current car” becomes the “previous car”.
🚓Move to the next car:
- The “next car” that you remembered becomes the “current car”.
🚓Repeat:
- Go back to step 2 and keep doing this until you run out of cars in the original train.
🚓The new head:
- When you run out of cars, the “previous car” is now the new head of the reversed train.
Example:
Imagine your train is: Car 1 -> Car 2 -> Car 3
Start: “previous car” is empty, “current car” is Car 1.
Remember: “next car” is Car 2.
Relink: Car 1 now links to nothing.
Move: “previous car” is Car 1, “current car” is Car 2.
Repeat:
“next car” is Car 3.
Car 2 links to Car 1.
“previous car” is car 2, “current car” is car 3.
Repeat:
next car is nothing.
Car 3 links to car 2.
“previous car” is car 3, “current car” is nothing.
Done! The new train is Car 3 -> Car 2 -> Car 1.
Implementation
Python
# # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""
Reverses a singly-linked list.
Args:
head: The head of the linked list.
Returns:
The head of the reversed linked list.
"""
prev_node = None # Initialize the previous node to None
curr_node = head # Initialize the current node to the head of the list
# Iterate through the linked list
while curr_node:
# Store the next node in a temporary variable
temp = curr_node.next
# Reverse the current node's pointer to point to the previous node
curr_node.next = prev_node
# Move the previous node pointer to the current node
prev_node = curr_node
# Move the current node pointer to the next node (stored in temp)
curr_node = temp
# After the loop, prev_node will be the new head of the reversed list
return prev_node
Typescript
// /**
// * Definition for singly-linked list.
// */
// class ListNode {
// val: number;
// next: ListNode | null;
// constructor(val?: number, next?: ListNode | null) {
// this.val = (val === undefined ? 0 : val);
// this.next = (next === undefined ? null : next);
// }
// }
function reverseList(head: ListNode | null): ListNode | null {
/**
* Reverses a singly-linked list.
*
* @param head - The head of the linked list.
* @returns The head of the reversed linked list.
*/
let prevNode: ListNode | null = null; // Initialize the previous node to null
let currNode: ListNode | null = head; // Initialize the current node to the head of the list
// Iterate through the linked list
while (currNode) {
// Store the next node in a temporary variable
const temp: ListNode | null = currNode.next;
// Reverse the current node's pointer to point to the previous node
currNode.next = prevNode;
// Move the previous node pointer to the current node
prevNode = currNode;
// Move the current node pointer to the next node (stored in temp)
currNode = temp;
}
// After the loop, prevNode will be the new head of the reversed list
return prevNode;
}
Go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
/**
* Reverses a singly-linked list.
*
* @param head - The head of the linked list.
* @returns The head of the reversed linked list.
*/
var prevNode *ListNode = nil // Initialize the previous node to nil
currNode := head // Initialize the current node to the head of the list
// Iterate through the linked list
for currNode != nil {
// Store the next node in a temporary variable
temp := currNode.Next
// Reverse the current node's pointer to point to the previous node
currNode.Next = prevNode
// Move the previous node pointer to the current node
prevNode = currNode
// Move the current node pointer to the next node (stored in temp)
currNode = temp
}
// After the loop, prevNode will be the new head of the reversed list
return prevNode
}
If you liked this article I’d appreciate an upvote or a comment. That helps me improve the quality of my posts as well as getting to know more about you, my dear reader.
Muchas gracias!
Follow me for more content like this.
X | PeakD | Rumble | YouTube | Linked In | GitHub | PayPal.me | Medium
Down below you can find other ways to tip my work.
BankTransfer: "710969000019398639", // CLABE
BAT: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
ETH: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875",
BTC: "33xxUWU5kjcPk1Kr9ucn9tQXd2DbQ1b9tE",
ADA: "addr1q9l3y73e82hhwfr49eu0fkjw34w9s406wnln7rk9m4ky5fag8akgnwf3y4r2uzqf00rw0pvsucql0pqkzag5n450facq8vwr5e",
DOT: "1rRDzfMLPi88RixTeVc2beA5h2Q3z1K1Uk3kqqyej7nWPNf",
DOGE: "DRph8GEwGccvBWCe4wEQsWsTvQvsEH4QKH",
DAI: "0x33CD7770d3235F97e5A8a96D5F21766DbB08c875"
Comments