欢迎访问我的leetcode题解目录https://blog.csdn.net/richenyunqi/article/details/80689211
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
算法设计:
遍历两个给定链表,将两个链表中的元素分别放入两个栈中,然后两个栈同时弹出元素,进行加和,用头插法插入新链表中。
C++代码:
class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { stack<int>s1,s2; for(;l1!=nullptr;l1=l1->next) s1.push(l1->val); for(;l2!=nullptr;l2=l2->next) s2.push(l2->val); int carry=0;//进位 ListNode*l3=nullptr;//新链表头指针 while(!s1.empty()||!s2.empty()||carry!=0){ int k1=0,k2=0; if(!s1.empty()){ k1=s1.top(); s1.pop(); } if(!s2.empty()){ k2=s2.top(); s2.pop(); } ListNode*p=new ListNode((k1+k2+carry)%10);//新建结点 p->next=l3; l3=p;//更新头指针 carry=(k1+k2+carry)/10;//更新进位 } return l3; } };