Reverse a signel list 12ms.use vector C++


  • 0
    A
    ListNode* reverseList(ListNode* head) {
        ListNode *tmp=NULL,*res = NULL,*dummy = new ListNode(0);
        vector<int> v;
        tmp = head;
        res = dummy;
        if(head == NULL || head->next == NULL)
            return head;
        while(tmp != NULL)
        {
            v.push_back(tmp->val);
            tmp = tmp->next;
        }
        for(int i = v.size()-1;i>=0;i--)
        {
            ListNode* t = new ListNode(0);  //初始化很重要
            t->val = v[i];
            dummy->next = t;
            dummy = dummy->next;
        }
        return res->next;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.