@@ -25,6 +25,10 @@ A linked list can be reversed either iteratively or recursively. Could you imple
2525
2626## 代码
2727
28+ 语言支持:JS,C++
29+
30+ JavaScript Code:
31+
2832``` js
2933/*
3034 * @lc app=leetcode id=206 lang=javascript
@@ -82,4 +86,88 @@ var reverseList = function(head) {
8286};
8387
8488```
89+ C++ Code:
90+ ``` C++
91+ /* *
92+ * Definition for singly-linked list.
93+ * struct ListNode {
94+ * int val;
95+ * ListNode *next;
96+ * ListNode(int x) : val(x), next(NULL) {}
97+ * };
98+ */
99+ class Solution {
100+ public:
101+ ListNode* reverseList(ListNode* head) {
102+ ListNode* prev = NULL;
103+ ListNode* cur = head;
104+ ListNode* next = NULL;
105+ while (cur != NULL) {
106+ next = cur->next;
107+ cur->next = prev;
108+ prev = cur;
109+ cur = next;
110+ }
111+ return prev;
112+ }
113+ };
114+ ```
115+ ## 拓展
116+
117+ 通过单链表的定义可以得知,单链表也是递归结构,因此,也可以使用递归的方式来进行reverse操作。
118+ > 由于单链表是线性的,使用递归方式将导致栈的使用也是线性的,当链表长度达到一定程度时,递归会导致爆栈,因此,现实中并不推荐使用递归方式来操作链表。
119+
120+ ### 描述
85121
122+ 1. 除第一个节点外,递归将链表reverse
123+ 2. 将第一个节点添加到已reverse的链表之后
124+
125+ > 这里需要注意的是,每次需要保存已经reverse的链表的头节点和尾节点
126+
127+ ### C++实现
128+ ```C++
129+ // 普通递归
130+ class Solution {
131+ public:
132+ ListNode* reverseList(ListNode* head) {
133+ ListNode* tail = nullptr;
134+ return reverseRecursive(head, tail);
135+ }
136+
137+ ListNode* reverseRecursive(ListNode *head, ListNode *&tail) {
138+ if (head == nullptr) {
139+ tail = nullptr;
140+ return head;
141+ }
142+ if (head->next == nullptr) {
143+ tail = head;
144+ return head;
145+ }
146+ auto h = reverseRecursive(head->next, tail);
147+ if (tail != nullptr) {
148+ tail->next = head;
149+ tail = head;
150+ head->next = nullptr;
151+ }
152+ return h;
153+ }
154+ };
155+
156+ // (类似)尾递归
157+ class Solution {
158+ public:
159+ ListNode* reverseList(ListNode* head) {
160+ if (head == nullptr) return head;
161+ return reverseRecursive(nullptr, head, head->next);
162+ }
163+
164+ ListNode* reverseRecursive(ListNode *prev, ListNode *head, ListNode *next)
165+ {
166+ if (next == nullptr) return head;
167+ auto n = next->next;
168+ next->next = head;
169+ head->next = prev;
170+ return reverseRecursive(head, next, n);
171+ }
172+ };
173+ ```
0 commit comments