167. 链表求和
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例
样例 1:
输入: 7->1->6->null, 5->9->2->null
输出: 2->1->9->null
样例解释: 617 + 295 = 912, 912 转换成链表: 2->1->9->null
样例 2:
输入: 3->1->5->null, 5->9->2->null
输出: 8->0->8->null
样例解释: 513 + 295 = 808, 808 转换成链表: 8->0->8->null
ListNode * addLists(ListNode * l1, ListNode * l2) {
// write your code here
std::queue<int> q1 ;
while(l1)
{
q1.push(l1->val);
l1 =l1->next;
}
std::queue<int> q2 ;
while(l2)
{
q2.push(l2->val);
l2 =l2->next;
}
std::queue<int> q3 ;
int num = 0;
while( !q1.empty() && !q2.empty())
{
int a = q1.front();
q1.pop();
int b = q2.front();
q2.pop();
int c = a + b + num;
int d = c % 10;
num = c /10;
q3.push(d);
}
while( !q1.empty())
{
int a = q1.front();
q1.pop();
int c = a + num;
int d = c % 10;
num = c /10;
q3.push(d);
}
while( !q2.empty())
{
int b = q2.front();
q2.pop();
int c = b + num;
int d = c % 10;
num = c /10;
q3.push(d);
}
if(num> 0)
{
q3.push(num);
}
//std:cout<<q3.size()<<std::endl;
ListNode * head=nullptr;
if(!q3.empty())
{
head = new ListNode(q3.front());
q3.pop();
}
ListNode * p = head;
while(!q3.empty())
{
ListNode* node = new ListNode(q3.front());
q3.pop();
p->next=node;
p=p->next;
}
return head;
}