leetcode 002-Add Two Numbers

problem:

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
Difficulty:Medium

note:

hint:

  • 用int或long来存储两个链表显然会产生溢出
  • 定义一个变量来判断是否存在进位

code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int len,flag,i,temp;
    int* num = (int*)malloc(1000*sizeof(int));
    temp = 0;              //temp保存是否存在进位
    len = 0;              //len表示两个整数相加最后的总长度
    while(l1 && l2){  //当两个数可以相加时的计算
        num[len++]=(l1->val+l2->val+temp)%10;
        temp = (l1->val+l2->val+temp)/10;
        l1 = l1->next;
        l2 = l2->next;
    }
    while(l1){      //当l2为空时,只计算l1和进位之间的和
        num[len++]=(l1->val+temp)%10;
        temp = (l1->val+temp)/10;
        l1 = l1->next;
    }
    while(l2){
        num[len++]=(l2->val+temp)%10;
        temp = (l2->val+temp)/10;
        l2 = l2->next;
    }
    if(temp!=0){  //判断是否还存在进位
        num[len++] = temp;
    }
    
    flag = 1;        //没有头结点的存在,故判断添加的节点是否为首元节点
    
    struct ListNode *l,*r;
    r = l;    //r指针用于定位链表的最后一个元素
    for(i = 0;i<len;i++){
        struct ListNode *s = (struct ListNode*)malloc(sizeof(struct ListNode));    //定义一个节点来存储新的元素
        s->val = num[i];
        s->next = NULL;
        if(flag){
            l = s;
            flag = 0;
        }else{
            r->next = s;
        }
        r = s;
    }
    return l;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容