链表-206. 反转链表
https://leetcode-cn.com/problems/reverse-linked-list/
1.题目描述
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表
2.思路
用二个指针,pre指向反转链表的首结点,curr指向链表的首结点,每次将curr->next指向pre
可以迭代,可以递归
3.1迭代法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *pre = nullptr;
ListNode *curr = head;
while(curr)
{
ListNode *p = curr;
curr = curr->next;
p->next = pre;
pre = p;
}
return pre;
}
};
3.2递归法
递归是逆序完成逆转,递归返回
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode *p = reverseList(head->next); //p always points to the last node of the linklist, which is also the first node of the reverseList
head->next->next = head;
head->next = nullptr; // the last node->next of the reverseList must point to null
return p;
}
};

浙公网安备 33010602011771号