Add Two Numbers
题目描述
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目分析
这是一道简单的链表应用题,题目用两个链表来分别存储两个非负整数,且从链表头结点到链表尾结点方向为整数的低位至高位反向,要求我们用新的链表按照题示格式存储两个整数相加的结果。
显然,只要耐心的去做,该题难度不大,只是有一些注意点需要格外小心:
- 两个整数的位数不同,不同情况对应不同解题过程;
- 进位方面,尤其是最高位运算之后是否还有 进位;
- 申请结点方面也需要各位注意。
完整C++代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *p, *q;
p = l1; q = l2;
ListNode *result = new ListNode(0);
ListNode *t = result;
ListNode *ti, *ttt;
int sum, x, y = 0; // 进位
bool te =false, emp = false;
while(1) {
sum = p->val + q->val + y;
x = sum % 10;
y = sum / 10;
t->val = x;
p = p->next;
q = q->next;
if (p==NULL && q==NULL) { // 如果两个整数位数相同
emp = true;
break;
} else if (p == NULL && q != NULL) { // 如果l2的位数多
ttt = q;
break;
} else if (p != NULL && q == NULL) {
ttt = p;
break;
}
ti = new ListNode(0);
t->next = ti;
t = ti;
}
if (emp) { // 如果位数相同
if (y == 1) { // 如果最高位运算完之后有进位
ti = new ListNode(1);
t->next = ti;
}
} else {
ti = new ListNode(0);
t->next = ti;
t = ti;
while(1) {
sum = ttt->val + y;
x = sum % 10;
y = sum / 10;
t->val = x;
ttt = ttt->next;
if(ttt == NULL) {
break;
}
ti = new ListNode(0);
t->next = ti;
t = ti;
}
if (y == 1) {
ti = new ListNode(1);
t->next = ti;
}
}
return result;
}
};
运行结果截图
分析与总结
但凡是链表的题目都要沉着冷静,不能太过大意,要仔细考虑清楚所有可能发生的情况