HELP C++ My recursive solution


  • 0
    J

    Hello everyone, is there anyone can tell me what's wrong with my solution? OJ shows Runtime error, but i test some examples and get the correct answer. Please help me.

    class Solution {
    public:
        void reorderList(ListNode* head) {
            if (head->next==NULL||head->next->next==NULL)
                return;
                
            ListNode *last = head, *tmp, *tail;
            
            while(last->next->next!=NULL)
            {
                last = last->next;
            }
            
            tail = last->next;
            
            tmp = head->next;
            head->next = tail;
            tail->next = tmp;
            last->next = NULL;
            reorderList(tmp);
            
            return;
        }
    };
    

  • 0
    J

    Thanks, solved.

    class Solution {
    public:
        vector<ListNode*> stack;
    
        void reorderList(ListNode* head) {
            if (head==NULL||head->next==NULL||head->next->next==NULL)
                return;
            if (stack.size()==0)
            {
                ListNode* a = head;
                while(a)
                {
                    stack.push_back(a);
                    a = a->next;
                }
                stack.pop_back();
            }
                
            ListNode *last = stack.back(), *tmp, *tail;
            stack.pop_back();
            
            tail = last->next;
            
            tmp = head->next;
            head->next = tail;
            tail->next = tmp;
            last->next = NULL;
            reorderList(tmp);
        }
    };
    

Log in to reply
 

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