题目链接:https://leetcode.com/problems/add-two-numbers-ii/description/
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
思路:
- 本题和2. Add Two Numbers类似,如果将本题中的链表节点进行逆置,则两道题就成了同一道题。可点击002. Add Two Numbers查看题解。
- Follow up中要求是否可以不逆置链表进行处理
- 既然不逆置链表进行处理,但是求解过程又是从链表尾结点开始处理的,很自然,就能想到栈(stack)这种数据结构,利用其FILO(First input Last output)即先进后出的性质。
- 操作步骤如下所述:
-
- 利用两个栈S1、S2分别记录两个链表的结点的val值,即压栈的过程;
- 然后对栈S1、S2中的元素进行出栈处理,将S1、S2中出栈元素的和压入栈S中。
- 最后将栈S中的元素进行出栈处理,并新建链表用指针head指向此链表的头结点,将出栈元素赋为新加入链表中结点的val值。
- 返回指针head。
编码如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 12 ListNode *p1 = l1; 13 ListNode *p2 = l2; 14 15 stack<int> s1, s2; 16 17 // 将链表l1中的数据压入栈s1 18 // 将链表l2中的数据压入栈s2 19 while (p1 != nullptr || p2 != nullptr) 20 { 21 if (p1 != nullptr) 22 { 23 s1.push(p1->val); 24 p1 = p1->next; 25 } 26 27 if (p2 != nullptr) 28 { 29 s2.push(p2->val); 30 p2 = p2->next; 31 } 32 } 33 34 // 将栈s1、栈s2中的元素进行加法操作 35 // 将相加后的元素压入栈s中 36 stack<int> s; 37 int carryBit = 0; 38 while (!s1.empty() && !s2.empty()) 39 { 40 int cur = s1.top() + s2.top() + carryBit; 41 int digit = cur % 10; 42 carryBit = cur / 10; 43 s.push(digit); 44 45 s1.pop(); 46 s2.pop(); 47 } 48 49 while (!s1.empty()) 50 { 51 int cur = s1.top() + carryBit; 52 int digit = cur % 10; 53 carryBit = cur / 10; 54 s.push(digit); 55 56 s1.pop(); 57 } 58 59 while (!s2.empty()) 60 { 61 int cur = s2.top() + carryBit; 62 int digit = cur % 10; 63 carryBit = cur / 10; 64 s.push(digit); 65 66 s2.pop(); 67 } 68 69 if (carryBit != 0) s.push(carryBit); 70 71 72 // 进行链表的赋值操作 73 ListNode *head = nullptr; 74 ListNode *p = nullptr; 75 while (!s.empty()) 76 { 77 ListNode *pTemp = new ListNode(s.top()); 78 if (head == nullptr) 79 { 80 head = pTemp; 81 p = head; 82 } 83 else 84 { 85 p->next = pTemp; 86 p = p->next; 87 } 88 89 s.pop(); 90 } 91 92 return head; 93 } 94 };