add-two-numbers
来源:互联网 发布:江苏普通发票软件下载 编辑:程序博客网 时间:2024/05/22 06:48
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
下面代码在牛客网发生段错误,但是我能想象的各种情况在vs里测试都没有问题,所以我是漏掉了什么情况没有考虑吗?
代码:
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };class Solution {public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode *dummy = new ListNode(-1); ListNode *temp = dummy; int carry = 0; while (l1 != NULL && l2 != NULL) { temp->next = l1; temp->next->val = l1->val + l2->val + carry; carry = temp->next->val / 10; temp->next->val %= 10; l1 = l1->next; l2 = l2->next; temp = temp->next; } //l1和l2位数相等但是有进位的情况 if (l1 == NULL && l2 == NULL && carry != 0) { ListNode *car = new ListNode(carry); temp->next = car; } //位数不等时同样需要把进位加上 if (l1 != NULL) { temp->next = l1; temp->next->val = l1->val + carry; } if (l2 != NULL) { temp->next = l2; temp->next->val = l2->val + carry; } return dummy->next; }};
阅读全文
0 0
- Add two numbers & Add binary
- LeetCode: Add Two Numbers
- Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode4: Add Two Numbers
- Leetcode : Add Two Numbers
- Add Two Numbers
- 【leetcode】Add Two Numbers
- add two numbers
- Add Two Numbers
- Add Two Numbers
- 高仿APP——元贝驾考
- LeetCode 476 Number Complement
- mongo添加索引以及解决Sort operation used more than the maximum 33554432 bytes of RAM
- Oracle数据库创建新用户并授予DBA权限
- 机器学习和图像处理(opencv)专用英语词典
- add-two-numbers
- docker ui 部署
- 利用Immutable解决React-Native那些因为对象被篡改导致的多次render问题
- Dijkstra算法求单源最短路径Java实现
- python识别图片验证码
- 解决flash插件被谷歌屏蔽
- 微信 HTML5 实现列表页与详情页无刷新返回 seesionStorage
- 热分析案例
- 肿瘤特征