LeeCode(2) Add Two Numbers C语言 版本

题目:
You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

思路:按照加法步骤,如果设置flag保存进位,按位相加,得出结果

C语言代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){

    struct ListNode* root = (struct ListNode*)malloc(sizeof(struct ListNode));
    
    struct ListNode* p =root;
    
    struct ListNode* l1temp =l1;
    struct ListNode* l2temp =l2;
    
    int flag = 0;
    int v =0;
    int temp =0;
    int num =0;
    while(l1temp !=NULL || l2temp!=NULL)
    {
        struct ListNode*q =(struct ListNode*)malloc(sizeof(struct ListNode));
        if(l1temp !=NULL && l2temp !=NULL)
        {
            temp =l1temp->val +l2temp->val +flag;
            
            v = temp%10;
            flag =temp /10;
            
            if(num ==0)
            {
                p->val =v;
                p->next =NULL;
                
            }
            else
            {
                q->val =v;
                q->next =NULL;
                p->next =q;
                p=p->next;
            }
            
           
            
            l1temp=l1temp->next;
            l2temp=l2temp->next;
        }
        else if(l1temp ==NULL)
        {
            temp = l2temp->val +flag;
            v = temp%10;
            flag =temp /10;
            q->val =v;
            q->next =NULL;
            p->next =q;
            p=p->next;
            l2temp=l2temp->next;
            
            
        }
       else if(l2temp ==NULL)
        {
            temp = l1temp->val +flag;
            v = temp%10;
            flag =temp /10;
            q->val =v;
            q->next =NULL;
            p->next =q;
            p=p->next;
            l1temp=l1temp->next;
        }
        
        num++;
       
    }
    
    if(flag!=0)
    {
            struct ListNode* tt =(struct ListNode*)malloc(sizeof(struct ListNode));
            tt->val =flag;
            tt->next =NULL;
            p->next =tt; 
    }
     return root;
}

效率:
LeeCode(2) Add Two Numbers C语言 版本_第1张图片

你可能感兴趣的:(leeCode)