leetcode 2:Add Two Numbers(C语言)

来源:互联网 发布:简易三维画图软件 编辑:程序博客网 时间:2024/06/03 16:53
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { 
    
   // if(l1==NULL)return l2;
//    if(l2==NULL)return l1;
    
    int addition = 0;
    int sum = 0;
    
    struct ListNode* res = (struct ListNode*)malloc(sizeof(struct ListNode)),*p=l1,*q=l2;
    res->val =0;
    res->next=NULL;
    struct ListNode* head = res;
    
    while(p!=NULL || q!=NULL){  
        res->val +=(p!=NULL?p->val:0) + (q!=NULL?q->val:0);
        
        if(res->val<=9)
            addition=0;
        else{
            addition=1;res->val-=10;
        } 
    
    printf("addition :%d",addition);
        if(      ((p!=NULL)?(p->next!=NULL):0)||((q!=NULL)?(q->next!=NULL):0)||addition==1)
        {
           res->next = (struct ListNode*)malloc(sizeof(struct ListNode));
           res->next->val=addition ;
           res->next->next=NULL;
           res=res->next;
           
        }
        
        if(p!=NULL)p=p->next;
        if(q!=NULL)q=q->next;
    } 
    return head;

}

*************? : 优先级问题导致一直通不过


0 0