mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Merge pull request #811 from touryung/master
更新 0206.翻转链表.md 添加递归解法思路 和 修复Java版本递归写法的问题
This commit is contained in:
@ -96,6 +96,28 @@ public:
|
||||
};
|
||||
```
|
||||
|
||||
我们可以发现,上面的递归写法和双指针法实质上都是从前往后翻转指针指向,其实还有另外一种与双指针法不同思路的递归写法:从后往前翻转指针指向。
|
||||
|
||||
具体代码如下(带详细注释):
|
||||
|
||||
```CPP
|
||||
class Solution {
|
||||
public:
|
||||
ListNode* reverseList(ListNode* head) {
|
||||
// 边缘条件判断
|
||||
if(head == NULL) return NULL;
|
||||
if (head->next == NULL) return head;
|
||||
|
||||
// 递归调用,翻转第二个节点开始往后的链表
|
||||
ListNode *last = reverseList(head->next);
|
||||
// 翻转头节点与第二个节点的指向
|
||||
head->next->next = head;
|
||||
// 此时的 head 节点为尾节点,next 需要指向 NULL
|
||||
head->next = NULL;
|
||||
return last;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
## 其他语言版本
|
||||
@ -135,9 +157,9 @@ class Solution {
|
||||
temp = cur.next;// 先保存下一个节点
|
||||
cur.next = prev;// 反转
|
||||
// 更新prev、cur位置
|
||||
prev = cur;
|
||||
cur = temp;
|
||||
return reverse(prev, cur);
|
||||
// prev = cur;
|
||||
// cur = temp;
|
||||
return reverse(cur, temp);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user