206.反转链表 递归,原地,栈,队列

这篇博客介绍了四种不同的链表反转方法:递归解法、原地操作解法、使用栈的解法以及使用队列的解法。每种方法都有详细的代码实现,适合学习数据结构和算法的读者参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

206. 反转链表

题目:

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

github题解仓库

解法一:

大致流程就是递归到链表的末尾,然后返回反转后的头结点,在返回的过程中反转,并传递回来这个头结点。

抓住reverseList函数返回的是目标链表的头结点这一点思考返回值,思考返回值该用什么接。

引入pre参数,原链表中各个结点head和head->next的关系(head是head->next前驱)在目标链表中会是相反的关系。
先写的第一版,然后多想一步就成了第二版。

class Solution {
public:
    ListNode* reverseList(ListNode* head, ListNode* pre = nullptr) {
        if(!head->next) {
            head->next = pre;
            return head;
        } 
        ListNode* ans = reverseList(head->next, head);
        head->next = pre;
        return ans;
    }
};
class Solution {
public:
    ListNode* reverseList(ListNode* head, ListNode* pre = nullptr) {
        if(!head) return pre;
        ListNode* ans = reverseList(head->next, head);
        head->next = pre;
        return ans;
    }
};

解法二:

另声明两个指针来原地操作

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head)   return nullptr;
        ListNode *pre = nullptr, *p;
        while(head->next) {
            p = head->next;
            head ->next = pre;
            pre = head;
            head = p;
        }
        head->next = pre;
        return head;
    }
};

解法三:

用栈存链表结点的值,再用尾插法直接生成反转后的链表

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *dummyhead = new ListNode(0);
        dummyhead->next = head;
        ListNode *r;
        stack<int> st;
        while(dummyhead->next != NULL) {
            r = dummyhead->next;
            st.push(r->val);
            dummyhead->next = r->next;
            delete r;
        }
        r = dummyhead;
        while(!st.empty()) {
            ListNode *temp = new ListNode(st.top());
            st.pop();
            temp->next = NULL;
            r->next = temp;
            r = temp;
        }
        return dummyhead->next;
    }
};

解法四:

用队列存链表结点的值,再用头插法生成反转后的链表

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *dummyhead = new ListNode(0);
        dummyhead->next = head;
        ListNode *r;
        queue<int> qu;
        while(dummyhead->next != NULL) {
            r = dummyhead->next;
            qu.push(r->val);
            dummyhead->next = r->next;
            delete r;
        }
        while(!qu.empty()) {
            ListNode *temp = new ListNode(qu.front());
            qu.pop();
            temp->next = dummyhead->next;
            dummyhead->next = temp;
        }
        return dummyhead->next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值