2015年7月28日 星期二

LEET code -Add Two Numbers

Add Two Numbers

 You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

一開始看不懂題目
範例的意思是 342+564=708  把她算出來
只是現在是反過來的
就只是簡單的指標運用
class DemoApp {
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    
   

   // if( l1 == NULL || l2 == NULL)return NULL;
    int incr=0;
    int sum=0;
    struct ListNode* point = (struct ListNode *)malloc(sizeof(struct ListNode));
    point->val=0;
    point->next=NULL;
    struct ListNode* ansRoot=point;
    while(l1 || l2 ||incr)
    {
        sum = ( l1!=NULL ?   l1->val:0)+(l2!=NULL ? l2-> val:0)+incr;
        incr = sum/10;
        sum%=10;
       // struct ListNode *temp = (struct ListNode*)malloc(sizeof(struct ListNode));
       // point->val=sum;
        point->next=(struct ListNode *)malloc(sizeof(struct ListNode));
        point = point->next;
        point->val=sum;
        point->next=NULL;
        
        if(l1)l1=l1->next;
        if(l2)l2=l2->next;
        
    }
    ansRoot=ansRoot->next;
    return ansRoot;
    
}
}


沒有留言:

張貼留言