Wrong Answer, why??????


  • 0
    X
    int initList(struct ListNode **L) {
    *L = (struct ListNode *) malloc(sizeof(struct ListNode));
    if(!*L) {
    	printf("error\n");
    	exit(0);
    }
    (*L)->next = NULL;
    return 1;
    }
    int push(struct ListNode *L, int pos, int e) {
    int i = 0;
    struct ListNode *q, *t;
    t = L;
    while(t && i < pos) {
    	t = t->next;
    	i++;
    }
    q = (struct ListNode *) malloc(sizeof(struct ListNode));
    if(!q) {
    	printf("error\n");
    	exit(0);
    }
    q->val = e;
    q->next = t->next;
    t->next = q;
    return 1;
    }
    int destory(struct ListNode **L) {
    struct ListNode *t;
    while(*L) {
    	t=(*L)->next;
    	free(*L);
    	*L=t;
    }
    return 1;
    }
    int traverse(struct ListNode *L) {
    struct ListNode *t = L->next;
    while(t) {
    	printf("%d ",t->val);
    	t = t->next;
    }
    printf("\n");
    return 1;
    }
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int i = 0;
    int total, increment = 0;
    struct ListNode *NewList;
    initList(&NewList);
    while(l1->next || l2->next || increment) {
    	total = 0;
    	if(l1->next) {
    		total += l1->next->val;
    		l1 = l1->next;
    	}
    	if(l2->next) {
    		total += l2->next->val;
    		l2 = l2->next;
    	}
    	total += increment;
    	increment = total/10;
    	push(NewList, i, total%10);
    	i++;
    }
    return NewList;
    }
    

    input: [0],[1]
    output: [0]
    It's output [1] in my computer, Can someone help me? thanks!


  • 0
    K

    Can you be more specific about your output?


  • 0
    X

    input: [0],[1] output: [0] in LeetCode, but it works on my computer output [1]


  • 0
    K

    I ran your code on my computer and it gave me [0] as a result. This is because your code does not add value when both l1 & l2 values exist. you are missing a line of code that adds l1 value, l2 value, and increment. Try to fix it and it will pass the test. However, you need to add more code for some special inputs. You will see when you submit your code.


  • 0
    X

    Thank you very much kedric, maybe I'm not the same as the structure of it, this is my main function:
    int main(void) {
    struct ListNode *L1, *L2, *NewList;
    int arr1[4] = {2,4,5,3};
    int arr2[3] = {5,6,4};
    int i;
    initList(&L1);
    initList(&L2);
    for(i=0; i<sizeof(arr1)/sizeof(arr1[0]); i++) {
    push(L1, i, arr1[i]);
    }
    for(i=0; i<sizeof(arr2)/sizeof(arr2[0]); i++) {
    push(L2, i, arr2[i]);
    }
    traverse(L1);
    traverse(L2);
    NewList = addTwoNumbers(L1, L2);
    traverse(NewList);
    destory(&L1);
    destory(&L2);
    destory(&NewList);
    return 0;
    }


  • 0
    K

    So, did you get your work?


  • 0
    X

    No, i mean it works using this main function


Log in to reply
 

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