Why slight change makes it "runtime error"?


  • 0
    C

    When I run this code, it gives me Runtime Error:

       class Solution {
        public:
            ListNode* reverseList(ListNode* head) {
                ListNode * prev = NULL;
                ListNode * curr = head;
                while((head->next) != NULL){
                  head = curr->next;
                  curr->next = prev;
                  prev = curr;
                  curr = head;
                }
                curr->next = prev;
                return head;
            }
        };
    

    After I change the last loop into

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            ListNode * prev = NULL;
            ListNode * curr = head;
            while(head!= NULL){
              head = curr->next;
              curr->next = prev;
              prev = curr;
              curr = head;
            }
            return prev;
        }
    };
    

    The answer becomes right. Why this happens?


  • 0
    R
    while((head->next) != NULL)
    

    head is possible to be NULL, and then head->next will lead to error.
    You just need to make sure head != NULL to run the loop, because even though head->next == NULL, you still need to run the loop to process the last node, just as you did in the second code.


Log in to reply
 

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