c++ solution but i get runtime error ,free():invalid pointer. please help me out


  • 0
    D

    /**

    • Definition for singly-linked list.
    • struct ListNode {
    • int val;
      
    • ListNode *next;
      
    • ListNode(int x) : val(x), next(NULL) {}
      
    • };
      */
    public:
        ListNode* oddEvenList(ListNode* head) {
            ListNode* t=head;
            int c=0,t1=-1,t2=-1,a[100],b[100];
            while(t!=NULL)
            {
                c++;
                t=t->next;
            }
            t=head;
            for(int i=1;i<=c;i++)
            {
              if(i%2==0)
              {
                  b[++t1]=t->val;
              }
              else
              {
                  a[++t2]=t->val;
              }
              t=t->next;
            }
            int i=t2+1;
            int j=0;
            ListNode* p,*p2;
            while(j<i)
            {
                ListNode* newnode=new ListNode(0);
                if(j==0)
                {
                   newnode->val=a[j];
                   p=newnode;
                   p2=newnode;
                }
                else
                {
                    newnode->val=a[j];
                    p2->next=newnode;
                    p2=newnode;
                }
                
                j++;
            }
            i=t1+1;
            j=0;
            while(j<i)
            {
                ListNode* newnode=new ListNode(0);
                newnode->val=b[j];
                p2->next=newnode;
                p2=newnode;
                j++;
            }
            return p;
            
            
            
        }
    };```

Log in to reply
 

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