The Reverse Linked List solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Reverse Linked List
C++, Python and TypeScript solutions for Reverse Linked List.
Solution files
Python•reverse-linked-list/synced-solution.py
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reverseList(head: ListNode) -> ListNode:
prev = None
current = head
while current:
next_temp = current.next
current.next = prev
prev = current
current = next_temp
return prev
C++•reverse-linked-list/synced-solution.cpp
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* current = head;
while (current) {
ListNode* nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
return prev;
}
};
TypeScript•reverse-linked-list/synced-solution.ts
function reverseList(head: ListNode | null): ListNode | null {
let prev: ListNode | null = null;
let current = head;
while (current) {
const nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
return prev;
}