C++:Leetcoed-链表-206反转链表

C++:Leetcoed-链表-206反转链表

熟悉链表的使用
加强对链表指针的理解,加强对双指针用法的理解



题目

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

有两种解法思路,双指针法和递归法

先介绍双指针法,递归法后续补上

双指针法

/*
Leetcode-206反转链表

1、双指针法
2、递归法

*/

#include "iostream"
#include "vector"
using namespace std;

//创建节点
class ListNode
{
public:
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *l_next) : val(x), next(l_next) {}
};

//创建链表类
class myLinkedList
{
public:
    int listSize;
    ListNode *dummyNode; //虚拟头结点
public:
    //构造函数初始化
    myLinkedList()
    {
        listSize = 0;
        dummyNode = new ListNode(0); //创建虚拟头节点
    }

    //创建链表
    ListNode *createList(vector<int> &nums)
    {
        ListNode *current = new ListNode(nums[0]);
        dummyNode->next = current;
        for (int i = 1; i < nums.size(); i++)
        {
            current->next = new ListNode(nums[i]);
            current = current->next;
        }

        listSize += nums.size();
    }

    //打印链表
    void printList()
    {
        ListNode *current = dummyNode->next;
        while (current != nullptr)
        {
            cout << current->val << "\t";
            current = current->next;
        }
        cout << endl;
    }

    //打印反转后链表
    void printReverseList(ListNode *head)
    {
        ListNode *current = head;
        while (current != nullptr)
        {
            cout << current->val << "\t";
            current = current->next;
        }
        cout << endl;
    }
};

//双指针法
//重点还是对于指针的理解
class Solution
{
public:
    ListNode *reverseList(ListNode *head)
    {
        ListNode *pre = nullptr;
        ListNode *cur = head;

        ListNode *temp;

        while (cur != nullptr)
        {
            temp = cur->next; //方便后续cur指针的移动
            cur->next = pre;

            pre = cur;
            cur = temp; //此处cur = cur->next,cur = pre->next都是错误!!!重点理解!!!!
                        //因为cur->next 此时也被pre赋值,并不是真正意义的next,
                        //pre此时与cur相同,所以pre->next==cur->next 一样是移动上来的pre,不是真正next
                        //所以需要temp来存cur->next
        }
        return pre; //cur为nullptr,pre才是反转后头结点
    }
};

int main(int argc, const char **argv)
{
    myLinkedList mylist;
    vector<int> nums = {1, 2, 3, 4, 5, 6};
    mylist.createList(nums);
    mylist.printList();
    Solution s1;
    ListNode *reverseNode;
    reverseNode = s1.reverseList(mylist.dummyNode->next);
    mylist.printReverseList(reverseNode);

    return 0;
}

总结

链表的熟练运用,双指针法的熟悉
参考代码随想录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值