LeetCodeAnimation/notes/LeetCode第206号问题:反转链表.md
程序员吴师兄 5dee53d957 更换图片地址
2019-11-14 11:00:28 +08:00

60 lines
1.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# LeetCode 206 号问题反转链表
> 本文首发于公众号五分钟学算法[图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>)系列文章之一。
>
> 个人网站[https://www.cxyxiaowu.com](https://www.cxyxiaowu.com)
题目来源于 LeetCode 上第 206 号问题反转链表题目难度为 Easy目前通过率为 45.8%
### 题目描述
反转一个单链表
**示例:**
```
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
```
**进阶:**
你可以迭代或递归地反转链表你能否用两种方法解决这道题
### 题目解析
设置三个节点`pre``cur``next`
- 1每次查看`cur`节点是否为`NULL`如果是则结束循环获得结果
- 2如果`cur`节点不是为`NULL`则先设置临时变量`next``cur`的下一个节点
- 3`cur`的下一个节点变成指向`pre`而后`pre`移动`cur``cur`移动到`next`
- 4重复123
### 动画描述
![](https://blog-1257126549.cos.ap-guangzhou.myqcloud.com/blog/voxlq.gif)
### 代码实现
```
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
while(cur != NULL){
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
```
![](https://blog-1257126549.cos.ap-guangzhou.myqcloud.com/blog/2z3t0.png)