add two numbersⅡ

来源:互联网 发布:p城办事处优化 编辑:程序博客网 时间:2024/05/22 06:51

题目描述:

You are given two linked lists representing two non-negative numbers. 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相比差别在于,数字的最高位在链表的头部,也就是说,相加的时候需要从链表的尾部开始加,容易想到的就是我采用stack,将链表的数字存入栈中,然后出栈想加,创建新节点保存进位,,这个步骤是为了之后处理最高进位,你也可以不这样做,到最后判断sum的值来选择是否创建新节点存最高位的进位;还有一点就是我存入新的链表的时候应该是头插法!

下面是完整代码:

#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){stack<int> s1,s2;listnode *cur = l1;while (cur != NULL){//入栈操作s1.push(cur->val);cur = cur->next;}listnode *cur2 = l2;while (cur2 != NULL){//入栈操作s2.push(cur2->val);cur2 = cur2->next;}int sum = 0;listnode *res = new listnode(0);while (!s1.empty() || !s2.empty()){if (!s1.empty()){sum += s1.top();s1.pop();}if (!s2.empty()){sum += s2.top();s2.pop();}res->val = sum % 10;sum = sum / 10;listnode *head = new listnode(sum);//保存每一次的进位,创建新的节点head->next = res;//头插法res = head;}return res->val == 0 ? res->next : res;//判断最高位是0还是1,0的话无需这个节点了}listnode *createlist(int n){listnode *newlistnode = new listnode(0);do{//创建新的链表,头插法listnode *cur=new listnode(n%10);cur->next = newlistnode;newlistnode = cur;n = n / 10;} while (n);return newlistnode;}void output(listnode *l){//输出链表,注意链表尾是不输出的,所以while判断条件是cur->nextlistnode *cur = l;while (cur->next){cout << cur->val<<" ";cur = cur->next;}cout << endl;}};int main(){solution s;int n, m;while (cin >> n >> m){listnode *l1 = s.createlist(n);listnode *l2 = s.createlist(m);s.output(l1);s.output(l2);listnode *l=s.addtwonumbers(l1, l2);s.output(l);}return 0;}


之后在网上百度解法的时候发现了这篇博客,感觉写的超级好,大牛的博客


原创粉丝点击