What is the difference between my two C++ solutions?


  • 0
    J

    I tried the following solution first, but I got runtime error:

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if(head == NULL) return head;
            
            ListNode *curr_node=head->next, *prev_node=head;
            prev_node->next = NULL;
            while(curr_node->next != NULL) {
                ListNode *next_node = curr_node->next;
                curr_node->next = prev_node;
                prev_node = curr_node;
                curr_node = next_node;
            }
            curr_node->next = prev_node;
            return curr_node;
        }
    };
    

    After reading some solutions from others posted here, I changed my solution as follows, and tried again, it got accepted.

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if(head == NULL) return head;
            
            ListNode *curr_node=head->next, *prev_node=head;
            prev_node->next = NULL;
            while(curr_node != NULL) {
                ListNode *next_node = curr_node->next;
                curr_node->next = prev_node;
                prev_node = curr_node;
                curr_node = next_node;
            }
            return prev_node;
        }
    };
    

    Could anybody remind me what's wrong with the first solution? Thanks in advance!


  • 0
    L

    What if the list has a single element, i.e. {1}. Then your curr_node is null. So when your first solution checks the condition in the while loop, null->next, it is getting run-time error.


Log in to reply
 

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