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