梁越

基本算法:逆转链表

0 人看过

算法难度:简单

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

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

用三个指针逆转

#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;
}