美文网首页
leetcode 002-Add Two Numbers

leetcode 002-Add Two Numbers

作者: 面包牛奶wlq | 来源:发表于2017-09-08 11:23 被阅读0次

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;
}

相关文章

网友评论

      本文标题:leetcode 002-Add Two Numbers

      本文链接:https://www.haomeiwen.com/subject/glsgjxtx.html