题目链接: 206. 反转链表 - 力扣(LeetCode)
迭代法
解题过程: 两个变量记录当前指针和前一个指针,再用临时变量记录当前变量的下一个结点,修改当前指针的指向,然后迭代临时变量赋值给当前指针,当前指针赋给前一个指针,临时变量记录当前指针的下一个,直到当前指针为空
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur=head,*pre=nullptr;
while(cur){
ListNode* temp=cur->next;//提前记录cur的下一个结点
cur->next=pre;//改变指针指向
//迭代
pre=cur;
cur=temp;
}
return pre;
}
};
- 时间复杂度:O(n)遍历整个链表
- 空间复杂度:O(1)
递归法
解题思路: 定义一个递归函数,两个参数为cur和pre,直到cur为空停止递归,返回pre(尾节点),开始回溯,回溯时修改指针指向
class Solution {
public:
ListNode* reverse(ListNode* cur,ListNode* pre){
if(cur==nullptr) return pre;//终止条件
ListNode* res=reverse(cur->next,cur);//记录返回结果
cur->next=pre;//改变指向
return res;
}
ListNode* reverseList(ListNode* head) {
return reverse(head,nullptr);
}
};
- 时间复杂度:O(n)遍历整个链表
- 空间复杂度:O(n)递归需要调用栈