原题地址:https://leetcode.com/problems/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
Subscribe to see which companies asked this question
1. 每个节点数值相加取个位数,把进位加到下一位。
2. 链表1和链表2不一定一样长,如果不一样长,在计算最后一个节点的时候,把短表中的节点值看作0。
3. 如果存在进位,进位要作为一个必须加入节点的值,简单说,链表1和链表2长度为3,在[2]位置相加存在进位,则,输出的链表的最后一位[3]为1,链表长度为4。
总的来说编程没什么难度,但要读懂题目,注意以上的注意点,下面放出我的实现代码:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* results=new ListNode(0);
ListNode* p = results;
int rise = 0;
while(true){
bool flag = false;
int num = l1->val + l2->val+rise;
p->val = num % 10;
if ((num / 10) > 0) {
rise = num / 10;
flag = true;
}
else {
rise = 0;
flag = false;
}
l1->val = 0;
l2->val = 0;
if (l1->next != NULL) {
l1 = l1->next;
flag = true;
}
if (l2->next != NULL) {
l2 = l2->next;
flag = true;
}
if (flag)p->next = new ListNode(0);
if (p->next == NULL)break;
p = p->next;
}
return results;
}
};