/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    int getLength(ListNode* head){
        int length = 0;
        ListNode* temp = head;
        while(temp != NULL){
            length++;
            temp = temp -> next;
        }
        return length;
    }
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        int pos = getLength(head) - n , cnt = 1;
        ListNode* temp = head;
        while(cnt != pos){
            temp = temp -> next;
            cnt++;
        }
        ListNode* nodeToDelete = temp -> next;
        temp -> next = temp -> next -> next;
        delete(nodeToDelete);
        return head;     
    }
};
Hey there I'm trying to solve this simple problem of removing the nth node from the end. But after running I'm facing a runtime error:
Line 27: Char 28: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:36:28
Aucun commentaire:
Enregistrer un commentaire