algorithm-base/animation-simulation/链表篇/leetcode206反转链表.md

184 lines
4.5 KiB
Java
Raw Normal View History

2021-03-23 12:08:09 +00:00
#### [206. ](https://leetcode-cn.com/problems/reverse-linked-list/)
**:**
> : 1->2->3->4->5->NULL
> : 5->4->3->2->1->NULL
AC
![](https://img-blog.csdnimg.cn/20210323191331552.gif)
low pro head
pro
pro pro = pro.next.
temp low
low = temp
2021-04-28 10:28:00 +00:00
****
2021-04-27 10:12:18 +00:00
Java Code:
2021-03-23 12:08:09 +00:00
```java
class Solution {
public ListNode reverseList(ListNode head) {
//特殊情况
if (head == null || head.next == null) {
return head;
}
//反转
return reverse(head);
}
public ListNode reverse (ListNode head) {
ListNode low = null;
ListNode pro = head;
while (pro != null) {
//代表橙色指针
ListNode temp = pro;
//移动绿色指针
pro = pro.next;
//反转节点
temp.next = low;
//移动黄色指针
low = temp;
}
return low;
}
}
```
2021-04-27 10:12:18 +00:00
JS Code:
```javascript
var reverseList = function(head) {
if(!head || !head.next) {
return head;
}
let low = null;
let pro = head;
while (pro) {
let temp = pro;
pro = pro.next;
temp.next = low;
low = temp;
}
return low;
};
```
2021-03-23 12:08:09 +00:00
2021-04-28 10:28:00 +00:00
C++
```cpp
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//特殊情况
if (head == nullptr || head->next == nullptr) {
return head;
}
//反转
return reverse(head);
}
ListNode * reverse (ListNode * head) {
ListNode * low = nullptr;
ListNode * pro = head;
while (pro != nullptr) {
//代表橙色指针
ListNode * temp = pro;
//移动绿色指针
pro = pro->next;
//反转节点
temp->next = low;
//移动黄色指针
low = temp;
}
return low;
}
};
```
2021-03-23 12:08:09 +00:00
2021-04-28 10:28:00 +00:00
****
2021-04-27 10:12:18 +00:00
Java Code:
2021-03-23 12:08:09 +00:00
```java
class Solution {
public ListNode reverseList(ListNode head) {
//结束条件
if (head == null || head.next == null) {
return head;
}
//保存最后一个节点
ListNode pro = reverseList(head.next);
//将节点进行反转。我们可以这样理解 4.next.next = 4;
//4.next = 5
//则 5.next = 4 则实现了反转
head.next.next = head;
//防止循环
head.next = null;
return pro;
}
}
```
2021-04-27 10:12:18 +00:00
JS Code:
```javascript
var reverseList = function(head) {
if (!head || !head.next) {
return head;
}
let pro = reverseList(head.next);
head.next.next = head;
head.next = null;
return pro;
};
```
2021-04-28 10:28:00 +00:00
C++:
```cpp
class Solution {
public:
ListNode * reverseList(ListNode * head) {
//结束条件
if (head == nullptr || head->next == nullptr) {
return head;
}
//保存最后一个节点
ListNode * pro = reverseList(head->next);
//将节点进行反转。我们可以这样理解 4->next->next = 4;
//4->next = 5
//则 5->next = 4 则实现了反转
head->next->next = head;
//防止循环
head->next = nullptr;
return pro;
}
};
```