题解 | #反转链表#

反转链表

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <iterator>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    ListNode* ReverseList(ListNode* head) {
        // write code here
        vector<int> ans;
        if(head == nullptr) return nullptr;

        while(head != NULL)
        {
            ans.push_back(head->val);
            head = head->next;
        }
        reverse(ans.begin(),ans.end());
        int n = ans.size();
        auto *head_2 = new ListNode(ans[0]);
        ListNode *tail = head_2;
        
        for(int i = 1 ; i < n ; i++)    
        {
            tail->next = new ListNode(ans[i]);
            tail = tail->next;   
        }
        return head_2;     
        
    }
};

本人是初学者,看到这题一来就想到的是先将链表的数存储到数组中,然后翻转数组,然后将数组输入到一个新的链表中。我本人遇到的最大问题是对于新建一个链表不够熟悉,问了很多次GPT。

全部评论

相关推荐

勤劳的鲸鱼在okr拆解:没有别的选择就去吧,有实习和没实习找工作是天上地下
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务