假定用链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。
样例
样例 1:
输入: 6->1->7 2->9->5
输出: 9->1->2
样例 2:
输入: 1->2->3 4->5->6
输出: 5->7->9
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param l1: The first list.
* @param l2: The second list.
* @return: the sum list of l1 and l2.
*/
ListNode * addLists2(ListNode * l1, ListNode * l2) {
// write your code here
vector<int> num1;
vector<int> num2;
ListNode*res=NULL;
int carry=0;
while(l1)
{
num1.push_back(l1->val);
l1=l1->next;
}
while(l2)
{
num2.push_back(l2->val);
l2=l2->next;
}
if(num1.size()<num2.size())
{
int len=num2.size()-num1.size();
for (int i = 0; i < len; i++) {
/* code */
num1.insert(num1.begin(),0);
}
}
if(num1.size()>num2.size())
{
int len=num1.size()-num2.size();
for (int i = 0; i < len; i++) {
/* code */
num2.insert(num2.begin(),0);
}
}
for (int i = num1.size()-1; i >= 0; i--) {
/* code */
int tmp=num1[i]+num2[i]+carry;
if(tmp>9) carry=1;
else carry=0;
ListNode *p=new ListNode(tmp%10);
p->next=res;
res=p;
}
if(carry) {ListNode*p=new ListNode(1); p->next=res; res=p;}
return res;
}
};