1.算法概述
遍历链表,并在遍历的过程中修改当前节点cur的next指针,使当前节点cur的next指针指向当前节点的前驱节点pre,遍历完之后pre指针就是逆序后链表的头指针。
2.图解
- 初始化
- 遍历节点
- 遍历结束
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;
}
};