题解 | #反转链表#

反转链表

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=295&tqId=23286&ru=/exam/oj&qru=/ta/format-top101/question-ranking&sourceUrl=%2Fexam%2Foj

/**

 * struct ListNode {

 *  int val;

 *  struct ListNode *next;

 *  ListNode(int x) : val(x), next(nullptr) {}

 * };

 */

class Solution {

  public:

//vector数组存储+反向赋值

    ListNode* ReverseList(ListNode* head) {

        // write code here

        if(!head || !head->next) return head;

        ListNode* p,*r;

        p=head;

        int n=0;

        vector<int> vec;

        while(p)

        {  

            n++;

            vec.push_back(p->val);

            p=p->next;

        }

        p=head;

        for(int i=n-1;i>=0;i--)

        {

            p->val=vec[i];

            p=p->next;

        }

        return head;

       

    }

};

全部评论

相关推荐

点赞 评论 收藏
分享
03-21 11:31
已编辑
门头沟学院 后端
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务