题目
给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
进阶:
如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
示例:
输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7
解析
这道题和Leetcode的第2题类似
由于链表的顺序反过来了,因此是没有办法一遍完成计算的,我们可以用两个栈先把数字都收集起来,再利用后进先出的特性进行计算
向新链表插入结果的时候也要注意用头插法
代码
/*** 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> s1, s2;while (l1) {s1.push(l1->val);l1 = l1->next;}while (l2) {s2.push(l2->val);l2 = l2->next;}ListNode* dummy = new ListNode(-1);// ListNode* h = dummy;int carry = 0, x, y;while (!s1.empty() || !s2.empty()) {if (s1.empty()) x = 0;else {x = s1.top();s1.pop();}if (s2.empty()) y = 0;else {y = s2.top();s2.pop();}int val = x + y + carry;ListNode* p = new ListNode(val % 10);p->next = dummy->next;dummy->next = p;carry = val / 10;}if (carry) {ListNode* p = new ListNode(1);p->next = dummy->next;dummy->next = p;}return dummy->next;}};
