一. 题目: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
Subscribe to see which companies asked this question.
二. 思路分析
给两个链表代表两个反向存储的数字,返回他们的和,用链表表示。思路比较简单,利用两个指针分别遍历两个链表,并且用一个变量表示是否有进位。某个链表遍历结束之后再将另一个链表连接在结果链表之后即可,若最后有进位需要添加一位。需注意以下几点。
1.因为链表存储是反过来的,所以加法进位时需要向后进位;
2.链表L1或L2为空时,直接返回,省掉多余的操作;
3.链表L1和L2长度可能不同,因此要注意处理某个链表剩余的高位;
4.2个数相加,可能会产生最高位的进位,因此要注意在完成以上1-3的操作后,判断进位是否为0,不为0则需要增加结点存储最高位的进位。
/**
* 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 *head = new ListNode(0);
ListNode *ptr = head;
int carry = 0;
while(true){
if(l1 != NULL){
carry += l1->val;
l1 = l1->next;
}
if(l2 != NULL){
carry += l2->val;
l2 = l2->next;
}
ptr->val = carry % 10;
carry /= 10;
if(l1 != NULL || l2 != NULL || carry != 0){
ptr = (ptr->next = new ListNode(0));
}else break;
}
return head;
}
};