Add Two Numbers

来源:互联网 发布:亚马逊数据 测评 编辑:程序博客网 时间:2024/06/18 12:30

问题描述:

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8


代码:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {    struct ListNode* res, *L1=l1, *L2=l2, *temp;    while (L1&&L2) {        L1->val=L2->val=L1->val+L2->val;        L1 = L1->next;        L2 = L2->next;    }    res = (L1) ? l1 : l2;    temp=res;    while (temp) {        if (temp->val>=10) {            if (!temp->next)             temp->next = (struct ListNode*)calloc(1,sizeof(struct ListNode));            temp->val-=10;            temp->next->val+=1;        }         temp = temp->next;    }    return res;}


0 0
原创粉丝点击