LeetCode 206. Reverse Linked List
LeetCode 206. Reverse Linked List
LeetCode 206. Reverse Linked List
LINK: https://leetcode.com/problems/reverse-linked-list/
Matter
You are given the head of a singly linked list.
Reverse the direction of the list so that all links point backward, and return the new head.
Example.
[1]
Input:
head = [1,2,3,4,5]
Output:
[5,4,3,2,1]
[2]
Input:
head = [1,2]
Output:
[2,1]
[3]
Input:
head = []
Output:
[]
Constraints
0 <= number of nodes <= 5000
-$5000$ <= Node.val <= $5000$
Problem analysis
The core of this problem is changing the direction of each node’s pointer.
In a singly linked list:
1
current -> next
Solution
Rearrange
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
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
ListNode* pNodeResult = nullptr;
do
{
std::vector<int> vctData;
while(true)
{
if(!head)
break;
vctData.push_back(head->val);
head = head->next;
}
if(!vctData.size())
break;
int i32Size = (int)vctData.size();
ListNode* pList = new ListNode;
ListNode* pListStart = pList;
for(int i = 0; i < i32Size-1; ++i)
{
pList->val = vctData[i32Size-1-i];
pList->next = new ListNode;
pList = pList->next;
}
pList->val = vctData[0];
pList->next = nullptr;
pNodeResult = pListStart;
}
while (false);
return pNodeResult;
}
};
Reuse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
ListNode* pListPrev = nullptr;
ListNode* pListCur = head;
while(true)
{
if(!pListCur)
break;
ListNode* pListNew = pListCur->next;
pListCur->next = pListPrev;
pListPrev = pListCur;
pListCur = pListNew;
}
return pListPrev;
}
};
This post is licensed under CC BY 4.0 by the author.