Why I got wrong answer?


  • 0
    T

    My code of "Add Two Numbers " as follows,
    for the first case
    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    my ouput on the OJ is 0->7->0
    but on my compilation is 7->0->8.

    Please help me...

    /**

    • Definition for singly-linked list.
    • struct ListNode {
    • int val;
      
    • struct ListNode *next;
      
    • };
      */
      typedef struct ListNode Node, *PNode;

    int isEmpty(PNode head)
    {
    if(head->next == NULL) {
    return 1;
    }
    else {
    return 0;
    }
    }

    PNode reverseLinkList(PNode head)
    {
    if(isEmpty(head)) {
    return head;
    }
    PNode rHead = (PNode) malloc(sizeof(Node));
    rHead->next = NULL;
    PNode tmp = head->next, tmpNext;
    while(tmp != NULL) {
    if(tmp->next != NULL) {
    tmpNext = tmp->next;
    }
    else {
    tmpNext = NULL;
    }
    tmp->next = rHead->next;
    rHead->next = tmp;
    tmp = tmpNext;
    }
    return rHead;
    }

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *result = (PNode)malloc(sizeof(Node));
    result->next = NULL;
    PNode p = result;

    PNode link1 = reverseLinkList(l1);
    PNode link2 = reverseLinkList(l2);
    
    PNode p1 = link1->next, p2 = link2->next;
    int carry = 0, addResult;
    PNode tmp;
    while(p1!= NULL && p2 != NULL) {
        addResult = carry + p1->val + p2->val;
        if(addResult / 10) {
            carry = 1;
            addResult = addResult % 10;
        }
        else {
            carry = 0;
        }
        tmp = (PNode)malloc(sizeof(Node));
        tmp->next = NULL;
        tmp->val = addResult;
        p->next = tmp;
        p = p->next;
        p1 = p1->next;
        p2 = p2->next;
    }
    while(p1 != NULL) {
        addResult = carry + p1->val;
        if(addResult / 10) {
            carry = 1;
            addResult = addResult % 10;
        }
        else {
            carry = 0;
        }
        tmp = (PNode)malloc(sizeof(Node));
        tmp->next = NULL;
        tmp->val = addResult;
        p->next = tmp;
        p = p->next;
        p1 = p1->next;
    }
    while(p2 != NULL) {
        addResult = carry + p2->val;
        if(addResult / 10) {
            carry = 1;
            addResult = addResult % 10;
        }
        else {
            carry = 0;
        }
        tmp = (PNode)malloc(sizeof(Node));
        tmp->next = NULL;
        tmp->val = addResult;
        p->next = tmp;
        p = p->next;
        p2 = p2->next;
    }
    
    return result;
    

    }


  • 0
    C

    why PNode p1 = link1->next, p2 = link2->next ?
    your condition of while is p1!= NULL && p2 != NULL. when list1 or list2 just has one val, it will pass.


Log in to reply
 

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