两个整数,每位的十进制表示都放到链表中,不过是倒序的,需要求出其结果。
原题如下:
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
其实代码不难。需要考虑两个情况。
1、某个链表为空的情况。
2、有可能链表空了,但是进位还有,这里需要加上节点。
这里给出代码如下:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *addTwoNumbers(ListNode *a, ListNode *b)
{
ListNode *head = NULL, *tail = NULL, *l = NULL;
int v, m = 0, c;
if (!a && !b) return NULL;
while (a && b){
v = a->val + b->val + m;
m = v / 10;
v %= 10;
if (!head) head = tail = new ListNode(v);
else {tail->next = new ListNode(v); tail = tail->next;}
a = a->next;
b = b->next;
}
a ? (l = a): (l = b);
while (l){
v = l->val + m;
m = v / 10;
v %= 10;
if (!head) head = tail = new ListNode(v);
else {tail->next = new ListNode(v); tail = tail->next;}
l = l->next;
}
while (m){
v = m % 10;
m /= 10;
if (!head) head = tail = new ListNode(v);
else {tail->next = new ListNode(v); tail = tail->next;}
}
return head;
}
但是上面的程序有个问题就是,在每个while循环中都有对于head 是否为空的判断,下面的代码可前置这个处理。
ListNode *addTwoNumbers(ListNode *a, ListNode *b)
{
ListNode *head = NULL, *tail = NULL, *l = NULL;
int v, m = 0, c = 0, d = 0;
if (!a && !b) return NULL;
if (a) {c = a->val; a = a->next;}
if (b) {d = b->val; b = b->next;}
v = c + d; m = v / 10; v %= 10;
head = tail = new ListNode(v);
while (a && b){
v = a->val + b->val + m;
m = v / 10;
v %= 10;
tail->next = new ListNode(v); tail = tail->next;
a = a->next;
b = b->next;
}
a ? (l = a): (l = b);
while (l){
v = l->val + m;
m = v / 10;
v %= 10;
tail->next = new ListNode(v); tail = tail->next;
l = l->next;
}
while (m){
v = m % 10;
m /= 10;
tail->next = new ListNode(v); tail = tail->next;
}
return head;
}