【Leetcode】2.Add Two Numbers 解题
来源:互联网 发布:360.cn 域名价格 编辑:程序博客网 时间:2024/05/01 20:29
【题目描述】:
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
【思路】:
以l1为基准,直接对其进行修改,避免了使用新链,new出很多个新节点。
【我的代码】:
1556 / 1556 test cases passed.
Runtime: 36 ms
Your runtime beats 63.70% of cppsubmissions.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *result = l1;//记录链首 ListNode *p = l1;//跟踪现需处理的节点 ListNode *tmpNode = new ListNode(0);//进位数据节点,临时存储 //对l1 l2并行处理 while (l1 && l2) { l1->val = l1->val + l2->val + tmpNode->val; tmpNode->val = l1->val / 10; l1->val = l1->val % 10; p = l1; l1 = l1->next; l2 = l2->next; } //l1 l2不同长度,l1 l2同一长度则可以跳过 ListNode *pre_p = p; if ((l1 && !l2) || (!l1 && l2)) { //l2长,l1长的话,p不变 if (!l1 && l2) { p->next = l2; } p = p->next; while (p) { p->val = p->val + tmpNode->val; tmpNode->val = p->val / 10; p->val = p->val % 10; pre_p = p; p = p->next; } } //如果最后还有进位,则新new一个节点 if (tmpNode->val != 0) { ListNode *q = new ListNode(tmpNode->val); pre_p->next = q; } return result; }};
0 0
- LeetCode 2. Add Two Numbers 解题报告
- [leetcode] 2. Add Two Numbers 解题报告
- LeetCode 2. Add Two Numbers 解题报告
- LeetCode: 2. Add Two Numbers 【C 解题】
- 【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解题]Add Two Numbers
- [leetcode]2. Add Two Numbers@Java解题报告
- Leetcode解题笔记 2.Add Two Numbers [Medium]
- 【LeetCode】Add Two Numbers 解题报告
- LeetCode-Add Two Numbers-解题报告
- Leetcode (2) Add Two Numbers 解题报告
- Leetcode #2 Add Two Numbers 解题小结
- [LeetCode] Add Two Numbers 解题报告
- [LeetCode 解题报告]002.Add Two Numbers
- codeforces
- Apache 的动态静态编译 &工作模式MPM
- Git命令总结
- 生成器模式
- Spring笔记整理
- 【Leetcode】2.Add Two Numbers 解题
- ZOJ-3752-The Three Guys【暴力】
- 福州大学第十二届程序设计竞赛-D - So Hard
- HDU2585
- tabFragment切换避免页面重叠
- 【HDU 2709】【水题】Sumsets
- Java防反编译技术
- spring3整合hibernate4的时候遇到的问题(Error applying BeanValidation relational constraints)
- 计算逆序对