Strange: very small code change gives right answer


  • 0
    D

    hey could you guys explain to me why the answer below is accepted :

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            
            if(head == NULL) return head;
            
            ListNode* second = head->next;
            head->next = NULL;
        
            while(second  != NULL){
                
                ListNode* third = second->next;
                second->next = head;
                
                /*Propragate pointers */
                head = second;
                second = third;
                
                
            }
            
            return head;
        }
    };
    

    while this one isn't?

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            
            if(head == NULL) return head;
            
            ListNode* second = head->next;
            ListNode* third = second->next;
            head->next = NULL;
        
            while(second  != NULL){
                
                third = second->next;
                second->next = head;
                
                /*Propragate pointers */
                head = second;
                second = third;
                
                
            }
            
            return head;
        }
    };
    

    It seems to not be happy with me initialising ListNode* third before the while loop but the logic should still be the same as I'm setting it to the same value right. It also works if I don't initialise the pointer but just declare it.


  • 1
    F

    The variable second could be NULL after "ListNode* second = head->next;", if the list contains only one node. This will result in a "Runtime Error" in "ListNode* third = second->next;". Hope that explains it.


Log in to reply
 

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