本文参考代码随想录
反转一个单链表
只需要改变链表指针next的指向,直接实现链表反转,无需定义新链表。
双指针法
首先定义一个cur指针指向头结点,再定义一个pre指针,初始化为null。
把cur->next节点用tmp指针保存
改变cur->next指针,指向pre.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* temp;
ListNode* cur = head;
ListNode* pre = NULL;
while(cur){
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
时间复杂度:O(n)
空间复杂度:O(1)
递归法
class Solution {
public:
ListNode* reverse(ListNode* pre, ListNode* cur){
if(cur == NULL) return pre;
ListNode* temp = cur->next;
cur->next = pre;
return reverse(cur, temp);
}
ListNode* reverseList(ListNode* head) {
return reverse(NULL, head);
}
};
时间复杂度:O(n)
空间复杂度:O(n),调用n层栈空间
递归法2
从后往前翻转指针朝向
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL) return NULL;
if(head->next == NULL) return head;
listNode *last = reverseList(head->next);
head->next->next=head;
head->next = NULL;
return last;
}
};
时间复杂度:O(n)
空间复杂度:O(n)
虚拟头结点
使用头插法实现翻转
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* dumpyHead = new ListNode(-1);
dumpyHead->next = NULL;
ListNode* cur = head;
while(cur != NULL){
ListNode* temp = cur->next;
cur->next = dumpyHead->next;
dumpyHead->next = cur;
cur = temp;
}
return dumpyHead->next;
}
};