Don't understand why my code gives a Runtime Error.


  • 0
    T
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *removeNthFromEnd(ListNode *head, int n) {
            int i,length=0;
            ListNode *cur,*prev,*dhead;
            dhead=(ListNode*)malloc(sizeof(ListNode));
            dhead->val=-1;
            dhead->next=head;
            for(cur=head;cur!=NULL;cur=cur->next)
                 length++;
            for(cur=dhead,i=0;i<=(length-n),cur!=NULL;i++,cur=cur->next)
            {
              prev=cur;   
            }
            prev->next=cur->next;
            free(cur);
            head=dhead->next;
            return head;
            
        }
    };`

Log in to reply
 

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