Can anybody help me? Why am I wrong


  • 0
    H

    struct ListNode* reverseList(struct ListNode* head) {
    struct ListNode *p=head->next;
    struct ListNode *tail=head;
    while(p){
    tail->next=p->next;
    p->next=tail;
    head=p;
    p=tail->next;
    }
    return head;

    }

    the wrong is: runtime error and the last execution is []


  • 0
    D

    I am pretty sure what was wrong was here

    struct ListNode *p=head->next;
    

    When one pass in NULL pointer as head. What your code would do is de-reference NULL, which is forbidden in almost all language and would result in SEGFAULT. Therefore causing a run time error.


  • 0
    H

    Thank you very much!You are right,I have modified my code,and this time it's right.

    struct ListNode* reverseList
    (struct ListNode* head) {
        struct ListNode *tail, *p;
       if(head){
        p=head->next;
        tail=head;
       }
      
        while(p){
           tail->next=p->next;
           p->next=head;
           head=p;
           p=tail->next;
        }
        return head;
        }


Log in to reply
 

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