Problem
Given the head
of a singly linked list, reverse the list, and return the reversed list.
Constraints:
- The number of nodes in the list is the range
[0, 5000]
. -5000 <= Node.val <= 5000
Solution
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ListNode *reverse_lis::reverseList(ListNode *head) {
ListNode* pre = nullptr;
ListNode* cur = head;
if (head == nullptr) {
return nullptr;
}
while (cur != nullptr) {
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
References
https://leetcode.com/problems/reverse-linked-list/?envType=study-plan&id=level-1