445. Add Two Numbers II。
来源:互联网 发布:医学搜题软件 编辑:程序博客网 时间:2024/05/16 11:31
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
这个题跟Add Two Numbers是一样的,但是这个是需要从链表的最后面开始进行相加。我的思路就是使用栈的特性,遍历两个链表,然后分别将两个链表中的内容存放到两个栈中,然后再根据栈中的数据分别出栈,这样每次出栈的元素的顺序就是原先链表从后往前的顺序。再使用跟之前那个一样的算数体系,使用一个变量保存两个数的总和,一个变量保存进位的数值。不断的创建新的节点,这里需要使用头插法来连接链表。
#include <iostream>#include <stack>using namespace std;struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* result = new ListNode(0); stack<int> nodes1; stack<int> nodes2; int carry = 0; int sum; while(l1 || l2) { if(l1) { nodes1.push(l1->val); l1 = l1->next; } if(l2) { nodes2.push(l2->val); l2 = l2->next; } } int n1,n2; while(!nodes1.empty() || !nodes2.empty()) {//因为两个栈的元素一样多 if(nodes1.empty()) { n1 = 0; } else { n1 = nodes1.top(); nodes1.pop(); } if(nodes2.empty()) { n2 = 0; } else { n2 = nodes2.top(); nodes2.pop(); } //cout << n1 << "," << n2 << endl; sum = n1 + n2 + carry; //cout << "sum:" << sum << endl; carry = sum / 10;//进的位数 result->val = sum % 10;//最后面一个节点赋值 ListNode* node = new ListNode(0); node->next = result; result = node; } if(carry) { result->val = carry; return result; } else { return result->next; } }};int main() { Solution s; ListNode node1(7); ListNode node2(2); ListNode node3(4); ListNode node4(3); ListNode node5(5); ListNode node6(6); ListNode node7(4); node1.next = &node2; node2.next = &node3; node3.next = &node4; node5.next = &node6; node6.next = &node7; ListNode* p = s.addTwoNumbers(&node1,&node5); while(p) { cout << p->val << endl; p = p->next; }}
运行结果可能有误差。
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II**
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II
- 445. Add Two Numbers II。
- 445. Add Two Numbers II
- 视图上的委托
- Java| Java对象克隆Clone(1)
- CentOS 6&7安装ffmpeg
- 字符串右移K位
- hdu 2899 导数求最值 浮点数二分
- 445. Add Two Numbers II。
- C语言介绍,C语言解答。
- Flex 布局教程:语法篇
- 自定义队列Queue
- HDU 3652 浅谈数位动态规划朝花夕拾Ver2.0
- Python中Unicode字符串
- PX4代码学习系列博客(6)——offboard模式位置控制代码分析
- tensorflow variable_scope,tf.name_scope, tf.variable, tf.get_varible
- #leetcode编程日记#343. Integer Break