实现反转链表

本文参考代码随想录

反转一个单链表

只需要改变链表指针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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值