反转链表|递归
反转链表
将链表反转过来,可以对比反转数组,但是链表由于不知道链表大小所以反转数组的方法在这里会变得复杂。这里有两种方法,双指针和递归法。
对应题目206. 反转链表🐾
双指针法
定义两个指针cur和pre分别指向一前一后,每次循环操作把cur的next指向pre再将cur和pre都向后移动一位,最后直到链表尾部,完成反转操作。分析复杂度,这里由于需要遍历一遍链表所以时间复杂度为\(O(N)\);由于没有产生新的链表所以空间复杂度为\(O(1)\)。
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = nullptr;
while(cur != nullptr) {
//define a temporary pointer to store the nexr of 'cur'.
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
递归法
对应着双指针的方法,使用递归的方式写出来,是的代码简洁。分析复杂度,时间复杂度与双指针法一样为\(O(N)\);由于是递归算法会调用栈空间所以空间复杂度也为\(O(N)\)。
ListNode* reverse(ListNode* cur,ListNode* pre) {
if(cur == nullptr)
return pre;
ListNode* temp = cur->next;
cur->next = pre;
return reverse(temp,cur);
}
ListNode* reverseList(ListNode* head) {
return reverse(head,nullptr);
}
浙公网安备 33010602011771号