LeetCode 2. Add Two Numbers
来源:互联网 发布:淘宝上卖的黑科技 编辑:程序博客网 时间:2024/04/28 16:23
题目
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
分析
变相大数加法, 较为不同的一点在于数据采用链表形式存储. 思路与普通大数加法相同, 只是结果储存于链表中. 计算过程中每计算一位, 分配一个 ListNode, 采用尾插法插入链表末尾. 值得注意的是, 最初
if (carry) { struct ListNode *ptmp = malloc(sizeof(struct ListNode)); ptmp->val = carry; p->next = ptmp; p = ptmp; }
后的代码为:
prst = prst->next; // point to the first element return prst;
提交后提示Runtime Error. 加入对链表头的内存释放后成功通过. 暂时不知道原因, 希望有高人可以帮忙解答.
p = prst; prst = prst->next; // point to the first element free(p); return prst;
解答
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *pa = l1, *pb = l2, *prst, *p; if (!pa || !pb) return NULL; p = prst = malloc(sizeof(struct ListNode)); prst->next = NULL; // head pointer, doesn't store data int carry = 0; while (l1 && l2) { int a = l1->val; int b = l2->val; int tmp = a + b + carry; carry = tmp / 10; struct ListNode *ptmp = malloc(sizeof(struct ListNode)); ptmp->val = tmp % 10; ptmp->next = p->next; p->next = ptmp; p = ptmp; l1 = l1->next; l2 = l2->next; } while (l1) { int a = l1->val; int tmp = a + carry; carry = tmp / 10; struct ListNode *ptmp = malloc(sizeof(struct ListNode)); ptmp->val = tmp % 10; ptmp->next = p->next; p->next = ptmp; p = ptmp; l1 = l1->next; } while (l2) { int b = l2->val; int tmp = b + carry; carry = tmp / 10; struct ListNode *ptmp = malloc(sizeof(struct ListNode)); ptmp->val = tmp % 10; ptmp->next = p->next; p->next = ptmp; p = ptmp; l2 = l2->next; } if (carry) { struct ListNode *ptmp = malloc(sizeof(struct ListNode)); ptmp->val = carry; p->next = ptmp; p = ptmp; } p = prst; prst = prst->next; // point to the first element free(p); return prst;}
0 0
- [LeetCode]2.Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode --- 2. Add Two Numbers
- [Leetcode] 2. Add Two Numbers
- 【leetcode】2. Add Two Numbers
- leetcode 2. Add Two Numbers
- LeetCode-2.Add Two Numbers
- [leetcode] 2. Add Two Numbers
- 【LeetCode】2. Add Two Numbers
- LeetCode - 2. Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode 2. Add Two Numbers
- Leetcode 2. Add Two Numbers
- 2. Add Two Numbers LeetCode
- leetcode 2. Add Two Numbers
- LeetCode-2. Add Two Numbers
- LeetCode 2. Add Two Numbers
- 2. Add Two Numbers----LeetCode
- 第十四章 c++中的代码重用
- IOS学习之—— xib的用法--自定义View
- c++ 单继承
- C++输入
- [leetcode-338]Counting Bits
- LeetCode 2. Add Two Numbers
- [Xcode]Xcode自动打ipa包脚本
- HDU 4059 The Boss on Mars
- IOS学习之——自定义代理delegate
- SQL Server 创建表 添加主键 添加列常用SQL语句
- eclipse中添加user library的方式
- DeviceMonitor Adb connection Error:远程主机强迫关闭了一个现有的连接 解决方法
- SVN命令
- Java 模板引擎总结