leetcode206:反转链表

题目链接

leetcode

题目描述

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

C++ 代码

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include <iostream>
#include <vector>
using namespace std;

// 链表结点的定义
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) {}
};

// 辅助函数:创建链表
ListNode* createList(const vector<int>& nums) {
ListNode* dummy = new ListNode(-1);
ListNode* cur = dummy;
for (int num : nums) {
cur->next = new ListNode(num);
cur = cur->next;
}
return dummy->next;
}

// 辅助函数:释放链表内存
void deleteList(ListNode* head) {
while (head != nullptr) {
ListNode* temp = head;
head = head->next;
delete temp;
}
}

// 辅助函数:打印链表
void printList(ListNode* head) {
while (head != nullptr) {
cout << head->val << " ";
if (head->next != nullptr) cout << "-> ";
head = head->next;
}
cout << endl;
}

/*
递归实现

reverseList 函数:反转一个链表,返回新链表的头结点(也是原链表的尾结点)。
1.递归处理 reverseList(head->next)。
2.以 head->next 为头结点的链表反转,得到原链表的尾结点 tail,此时 head->next 是新链表的尾结点。
3.将它的 next 指向 head,将 head->next 指向空。将整个链表反转,新链表的头结点是 tail。

时间复杂度:O(n)
其中 n 是链表的长度。遍历链表一次。
空间复杂度:O(n)
总共递归 n 层,系统栈的空间复杂度是 O(n),所以需要额外 O(n) 的空间。
*/
class Solution_0 {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}

ListNode* tail = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return tail;
}
};

/*
迭代实现
未使用虚拟头结点,使用三个指针。
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}

ListNode *prev = nullptr, *cur = head;
while (cur != nullptr) {
ListNode* temp = cur->next;
cur->next = prev;
prev = cur;
cur = temp;
}

return prev;
}
};

int main() {
Solution solution;
vector<vector<int>> head_cases = {
{1,2,3,4,5},
{1,2},
{}
};

for (size_t i = 0; i < head_cases.size(); i++) {
// 创建原始链表
ListNode* head = createList(head_cases[i]);
cout << "Original List: ";
printList(head);

// 反转链表
ListNode* reversedHead = solution.reverseList(head);
cout << "Reversed List: ";
printList(reversedHead);

// 释放内存
deleteList(reversedHead);
}

return 0;
}

leetcode206:反转链表
https://lcf163.github.io/2024/04/20/leetcode206:反转链表/
作者
乘风的小站
发布于
2024年4月20日
许可协议