- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0206-reverse-linked-list.cpp
34 lines (31 loc) · 886 Bytes
/
0206-reverse-linked-list.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
206. Reverse Linked List
Submitted: October 21, 2024
Runtime: 0 ms (beats 100.00%)
Memory: 13.06 MB (beats 40.91%)
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
classSolution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr) return head;
if (head->next == nullptr) return head;
ListNode* new_head = head;
while (head->next != nullptr) {
ListNode* head_next = head->next;
head->next = head_next->next;
head_next->next = new_head;
new_head = head_next;
} // remove node after original head and add to front
return new_head;
}
};