#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Definition for singly-linked list. */
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
int carry = 0;
struct ListNode dummy;
struct ListNode *p = l1, *prev = &dummy;
dummy.next = p;
while (l1 != NULL || l2 != NULL) {
int sum = 0;
if (l1 != NULL) {
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
if (p == NULL) {
/* l2 longer than l1 */
prev->next = l2;
p = l2;
}
sum += l2->val;
l2 = l2->next;
}
sum += carry;
carry = sum / 10;
p->val = sum % 10;
prev = p;
p = p->next;
}
if (carry) {
p = malloc(sizeof(*p));
p->val = carry;
p->next = NULL;
prev->next = p;
}
return dummy.next;
}
static struct ListNode *node_build(const char *digits)
{
struct ListNode *res, *p, *prev;
int first = 1;
int len = strlen(digits);
const char *c = digits + len - 1;
prev = NULL;
while (len-- > 0) {
p = malloc(sizeof(*p));
if (first) {
first = 0;
res = p;
}
p->val = *c-- - '0';
p->next = NULL;
if (prev != NULL) {
prev->next = p;
}
prev = p;
}
return res;
}
static void show(struct ListNode *ln)
{
int sum = 0, factor = 1;
while (ln != NULL) {
sum += ln->val * factor;
factor *= 10;
ln = ln->next;
}
printf("%d\n", sum);
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "Usage: ./test n1 n2\n");
exit(-1);
}
struct ListNode *l1 = node_build(argv[1]);
struct ListNode *l2 = node_build(argv[2]);
struct ListNode *res = addTwoNumbers(l1, l2);
show(l1);
show(l2);
show(res);
return 0;
}

__AtYou__
- 粉丝: 3534
最新资源
- TMMS8.0 beta demo script (For IOS).pdf
- tmms_9.6_ag.pdf
- tmms_9.6_IDG.pdf
- tmms_9_5_idg.pdf
- TMMS 8 部署简要清单.pdf
- Instructions for TMMS Migration_updated_20140123.pdf
- tmms_9.5_ag.pdf
- [TMMS_9.1]AG.pdf
- [TMMS_9.0]IDG.pdf
- [TMMS_9.1]IDG.pdf
- [TMMS_9.0]AG.pdf
- [TMMS 8.0] Administrator's Guide.pdf
- [TMMS 8.0] Installation and Deployment Guide.pdf
- 从TMMS8升级至9.txt
- tmms-ee_9.6_readme_ios.txt
- tmms-ee_9.6_readme_server.txt
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈


