Why my code got wrong answer? C++


  • 1
    Y
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if(!head) return NULL;
            if(!head->next) return head;
            ListNode* prev = NULL;
            ListNode* cur = head;
            ListNode* nex = cur->next;
            while(!cur){
                cur->next = prev;
                prev = cur;
                cur = nex;
                nex=nex->next;
            }
            return prev;
        }
    };
    

    Input: [1, 2]
    Output: []
    Expect: [2, 1]

    I have read some others' codes. I think the basic idea is the same, but why my code got the wrong answer?


  • 0
    G

    It is because while(!cur), it is the reason why I always use cur != NULL.
    But your code will still give you error.


  • 0
    M

    Hello,

    First off, use cur != NULL instead of !cur. But this condition will make nex NULL in the last loop and there will be runtime error. Think about changing the condition to next != NULL and return cur.


  • 0
    Y

    Yes. That's the reason. Thanks for your answer.


Log in to reply
 

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