反转链表

来源:互联网 发布:淘宝店铺上架宝贝数量 编辑:程序博客网 时间:2024/06/05 21:00

题目

输入一个链表,反转链表后,输出链表的所有元素。

思路

类似于链表的头插法,每次取下一个节点,把这个节点的next指向已经取下的部分的头结点。

参考代码

/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};*/class Solution{public:    ListNode* ReverseList(ListNode* pHead)    {        if (pHead == nullptr) return pHead;        ListNode* now = nullptr;        while (pHead->next != nullptr)        {            ListNode* temp = pHead->next;            pHead->next = now;            now = pHead;            pHead = temp;        }        pHead->next = now;        return pHead;    }};
原创粉丝点击