Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题意解析:
这道题刚拿到手没弄明白啥意思。我这里解释一下,这道题其实就是465+342=807
只不过465和342都使用链表表示,且是逆序的。
理解完题意我觉得这道题就不困难了。只需要注意每个链表节点都只存放一位数字,因此需要考虑进位问题。
代码:
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2)
{
ListNode * l3 = new ListNode(0); //保存相加结果
ListNode * a = l1, *b = l2, *c = l3; //保存原始链表,用两个指针分别去遍历两个链表
bool carry = false; //进位操作标志位
int value = 0;
while(a && b) //a和b都不为空
{
value = a->val + b->val;
if(carry)
{
value = value + 1; //前一次运算的进位
carry = false;
}
if(value > 9)
{
carry = true;
value = value%10;
}
ListNode *s = new ListNode(value);
c->next = s;
c = c->next;
a = a->next;
b = b->next;
}
while(a) // a != NULL
{
value = a->val ;
if(carry)
{
value = value + 1; //前一次运算的进位
carry = false;
}
if(value > 9)
{
carry = true;
value = value%10;
}
ListNode *s = new ListNode(value);
c->next = s;
c = s;
a = a->next;
}
while(b) // b != NULL
{
value = b->val ;
if(carry)
{
value = value + 1; //前一次运算的进位
carry = false;
}
if(value > 9)
{
carry = true;
value = value%10;
}
ListNode *s = new ListNode(value);
c->next = s;
c = s;
b = b->next;
}
if(carry)
{
ListNode *s = new ListNode(1);
c->next = s;
}
l3 = l3->next; //去掉第一个空节点
return l3;
}
};
测试代码:(包含将一个非负数转换成逆序链表表示)
#include <iostream>
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void print(ListNode * l)
{
ListNode * a = l;
while(a)
{
cout<<a->val<<" ";
a = a->next;
}
cout<<endl;
}
int main()
{
int num1 = 9721123;
int num2 = 134;
ListNode * l1 = new ListNode(0);
ListNode * l2 = new ListNode(0);
ListNode *a = l1, *b = l2;
int bits = 0; //个位数
while(num1)
{
bits = num1%10;
num1 /= 10;
ListNode *s = new ListNode(bits);
a->next = s;
a = s;
}
l1 = l1->next; //去掉第一个空节点
print(l1);
while(num2)
{
bits = num2%10;
num2 /= 10;
ListNode *s = new ListNode(bits);
b->next = s;
b = s;
}
l2 = l2->next; //去掉第一个空节点
print(l2);
Solution sol;
ListNode * l3;
l3 = sol.addTwoNumbers(l1,l2);
print(l3);
return 0;
}