LeetCode 445. Add Two Numbers II(链表求和)

题意:两个非空链表求和,这两个链表所表示的数字没有前导零,要求不能修改原链表,如反转链表。

分析:用stack分别存两个链表的数字,然后从低位开始边求和边重新构造链表。

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
/**
 * 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 *cur = new ListNode(0);
        while(!s1.empty() || !s2.empty()){
            if(!s1.empty()){
                cur -> val += s1.top();
                s1.pop();
            }
            if(!s2.empty()){
                cur -> val += s2.top();
                s2.pop();
            }
            ListNode* pre = new ListNode(cur -> val / 10);
            cur -> val %= 10;
            pre -> next = cur;
            cur = pre;
        }
        return (cur -> val == 0) ? cur -> next : cur;
    }
};

  

猜你喜欢

转载自www.cnblogs.com/tyty-Somnuspoppy/p/12348096.html