双指针法(好理解):
- pre 和 cur ;pre 在前 cur 在后。
- 每次让 pre的 next 指向 cur ,实现一次局部反转局部反转完成之后
- pre和 cur同时往前移动一个位置
- 循环上述过程,直至 pre 到达链表尾部
pre->next = cur;
cur = pre;纠正绿色第三行
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = NULL, *pre = head;
while (pre != NULL) {
ListNode* t = pre->next;
pre->next = cur;
cur = pre;
pre = t;
}
return cur;
}
};
拓展:迭代解法
使用递归函数,一直递归到链表的最后一个结点,该结点就是反转后的头结点,记作 retret 此后,每次函数在返回的过程中,让当前结点的下一个结点的 nextnext 指针指向当前节点。同时让当前结点的 nextnext 指针指向 NULLNULL ,从而实现从链表尾部开始的局部反转当递归函数全部出栈后,链表反转完成。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* ret = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return ret;
}
};