Leetcode Add Two Numbers II
来源:互联网 发布:2016年网络流行词汇 编辑:程序博客网 时间:2024/05/16 09:26
题意:将两个以链表形式存储的数字向加,并以链表形式输出。
思路:先按位向加,最后将链表颠倒。
/** * 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) { stack<int> sl1; stack<int> sl2; ListNode* next = l1; while(next) { sl1.push(next->val); next = next->next; } next = l2; while(next) { sl2.push(next->val); next = next->next; } ListNode* myhead = new ListNode(0); next = myhead; int c = 0; while(!sl1.empty() || !sl2.empty()) { int a = 0; int b = 0; if(!sl1.empty()) { a = sl1.top(); sl1.pop(); } if(!sl2.empty()) { b = sl2.top(); sl2.pop(); } ListNode* temp = new ListNode((a + b + c) % 10); c = (a + b + c) / 10; next->next = temp; next = temp; } if(c) { ListNode* temp = new ListNode(c); next->next = temp; next = temp; } //show the result // reverse next = myhead->next; ListNode* pre = NULL; while(next) { cout << next->val << endl; ListNode* temp = next->next; next->next = pre; pre = next; next = temp; } return pre; }};
0 0
- [LeetCode]Add Two Numbers II
- Add Two Numbers II ---LeetCode
- Leetcode Add Two Numbers II
- LeetCode-Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- leetcode-445. Add Two Numbers II
- Leetcode Add Two Numbers II 445
- LeetCode 445. Add Two Numbers II
- [LeetCode]445. Add Two Numbers II
- leetcode 445 Add Two Numbers II C++
- LeetCode 445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- 【LeetCode】 445. Add Two Numbers II
- LeetCode笔记:445. Add Two Numbers II
- leetcode 445. Add Two Numbers II
- 【Leetcode】445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- LeetCode 445. Add Two Numbers II
- 【cocos优化】
- 急急急!!!请教一个关于ASP不报错的问题!浪费一下午的时间啊。。。。。。
- bzoj 3489: A simple rmq problem (KD-tree)
- 安卓模拟器配置了摄像头还是显示黑白棋盘
- bug宝典JAVA篇 BeanUtils.copyProperties 日期问题
- Leetcode Add Two Numbers II
- 如何使用ocilib进行oracle8的读取
- Qt学习笔记(1)---QT5利用事件过滤器实现在控件上绘图
- android工程生成jar包
- 地图API和androidSDK版本高了和低版本有没有冲突
- Shared Library Search Paths
- 安卓开源框架android-async-http-master最新版的应该怎么用啊,求大神指导
- 2016总结,真正新的里程碑和新起点
- 程序猿的机器学习之路-1-Numpy基础:创建多维数组