You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
問題描述:從左到右加法計算,滿10進位.
思路:很簡單,三個變量表示進位值step(0,1),當前的目的鏈表中的存入值value,以及sum. 注意的是最後要判斷step是否爲1,如果爲1還要再創建一個節點。
附加代碼:
#include<iostream>
#include<vector>
#include<string>
#include<map>
#include<unordered_map>
#include<stdio.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int step = 0, sum = 0, value = 0;
ListNode *p = new ListNode(0);
ListNode *phead = p;
//遍歷
while (l1 != NULL && l2 != NULL)
{
sum = l1->val + l2->val + step;
step = sum / 10;
value = sum % 10;
ListNode *pnode = new ListNode(value);
//更新目的鏈表
p->next = pnode;
p = pnode;
//更新原鏈表
l1 = l1->next;
l2 = l2->next;
}
while (l1 != NULL)
{
sum = l1->val + step;
step = sum / 10;
value = sum % 10;
ListNode *pnode = new ListNode(value);
p->next = pnode;
p = pnode;
l1 = l1->next;
}
while (l2 != NULL)
{
sum = l2->val + step;
step = sum / 10;
value = sum % 10;
ListNode *pnode = new ListNode(value);
p->next = pnode;
p = pnode;
l2 = l2->next;
}
if (step != 0)
{
ListNode *pnode = new ListNode(step);
p->next = pnode;
}
return phead->next;
}
void printList(ListNode *pl)
{
while (pl != NULL)
{
cout << pl->val << " ";
pl = pl->next;
}
cout << endl;
}
ListNode *creatList(vector<int> vec)
{
ListNode *p = new ListNode(0);
ListNode *phead = p;
for (int i = 0; i < vec.size(); ++i)
{
ListNode *ptmp = new ListNode(vec[i]);
p->next = ptmp;
p = ptmp;
}
return phead->next;
}
int main()
{
vector<int> vec = { 3,5,7 };
ListNode *p = creatList(vec);
printList(p);
vector<int> vec1 = { 3,5,7 };
ListNode *p1 = creatList(vec1);
printList(p1);
ListNode *p2 = addTwoNumbers(p, p1);
printList(p2);
system("pause");
return 0;
}