leetcode-个人题解2

LEETCODE专题


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

下面是一些个人理解和细节把握:

  1. 链表的每个节点其实都可以相加然后往下走到下一个节点,但是要把握好前提条件:

    1. 两个链表要保持同一个深度
    2. 每一个节点相加后的进位要存储至结果链表的下一个节点

    这些都是可以做到的,下面有代码,在这里不再赘述

2.在1[1]的基础上提出问题:倘若两个链表不等长怎么办?
这时候就加一个条件判断就能够解决问题

3.最后倘若两个输入链表已经结束然而进位为1,则要在结果链表的尾端新建一个结果节点,将进位存进去


下面直接上代码:

/**
 * 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) {
        bool first = true;                    // firstly enter the while block
        int carry = 0;                        // carry = 1 or 0
        ListNode * sum = new ListNode(0);     // store the sum of l1 and l2
        ListNode * head_of_sum = sum;         // return the head of ListNode * sum
        while (l1 != NULL || l2 != NULL) {
            int temp_sum = carry;

            if (first == false) {
                sum->next = new ListNode(0);
                sum = sum->next;
            } else {
                first = false;
            }

            if (l1 == NULL) {
                temp_sum += l2->val;
            } else if (l2 == NULL) {
                temp_sum += l1->val;
            } else {
                temp_sum += l1->val + l2->val;
            }

            carry = temp_sum / 10;
            sum->val = temp_sum % 10;

            if (l1 != NULL) {
                l1 = l1->next;
            }
            if (l2 != NULL) {
                l2 = l2->next;
            }
        }

        if (carry == 1) {
            sum->next = new ListNode(carry);
        }
        return head_of_sum;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章