206. Reverse Linked List
Solutions
To reverse a linked list, we provides recusive
and non reusive
way to do this.
1 -> 2 -> 3 -> 4 -> ... -> N
now, we need to swap the arrow like this:
1 <- 2 <- 3 <- 4 <- ... <- N
first round:
- prev = nullptr, head = 1, next = 2
ListNode *reverseList(ListNode *head) {
if (head == nullptr) {
return nullptr;
}
if (head->next == nullptr) {
return head;
}
ListNode *prev = nullptr;
ListNode *curr = head;
ListNode *next = nullptr;
while (curr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
date: 2025-05-22
tags:
- leetcode/linked-list
status: Easy