前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >基本算法:逆转链表

基本算法:逆转链表

作者头像
opencode
发布2022-12-26 13:59:46
1910
发布2022-12-26 13:59:46
举报
文章被收录于专栏:知识同步

算法难度:简单

我永远记得这个题,让我在字节的一面挂了

给你一个链表,输入链表头,返回逆转后的链表

用三个指针逆转

代码语言:javascript
复制
#include <iostream>
using namespace std;

struct ListNode
{
public:
    int val;
    struct ListNode *next;
};

class Solution {
public:
    ListNode *ReverseList(ListNode *pHead)
    {
        ListNode *p0 = nullptr;
        ListNode *p1 = pHead;
        ListNode *p2 = pHead->next;
        while (p1)
        {
            p1->next = p0;
            //p2->next=p1;   /*这个不能加,p2不需要指向p1*/

            p0 = p1;
            p1 = p2;
            if (p2) p2 = p2->next;
        }

        return p0;
    }
};

int main()
{
    ListNode list[5];
    list[0].val = 1;
    list[0].next = &list[1];
    list[1].val = 2;
    list[1].next = &list[2];
    list[2].val = 3;
    list[2].next = &list[3];
    list[3].val = 4;
    list[3].next = &list[4];
    list[4].val = 5;
    list[4].next = NULL;

    ListNode *node = list;
    cout << endl;
    Solution solu;
    node = solu.ReverseList(list);
    while (node != NULL)
    {
        cout << node->val;
        node = node->next;
    }
    cout << endl;
    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-07-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档