![](https://img.haomeiwen.com/i4633461/51d775fa6e90e701.jpg)
1.算法概述
遍历链表,并在遍历的过程中修改当前节点cur的next指针,使当前节点cur的next指针指向当前节点的前驱节点pre,遍历完之后pre指针就是逆序后链表的头指针。
2.图解
- 初始化
![](https://img.haomeiwen.com/i4633461/e5a3ef85eecd548b.png)
- 遍历节点
![](https://img.haomeiwen.com/i4633461/9ab2088961749b1a.png)
- 遍历结束
![](https://img.haomeiwen.com/i4633461/d2dc028dd1443800.png)
3.代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode * pre = NULL;
ListNode * cur = head;
while (head)
{
head = head->next;
cur->next = pre;
pre = cur;
cur = head;
}
return pre;
}
};
网友评论