LeetCode 2. Add Two Numbers

2019-03-22  本文已影响0人  cb_guo

题目描述

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.

Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

题目思路

代码 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* p1 = l1;
        ListNode* p2 = l2;
        ListNode* head = NULL;
        ListNode* tail = NULL;
        int sum = 0;
        
        while(p1!=NULL || p2!=NULL){
            sum = sum / 10;
            if(p1!=NULL){
                sum = sum + p1->val;
                p1 = p1->next;
            }
            if(p2!=NULL){
                sum = sum + p2->val;
                p2 = p2->next;
            }
            
            ListNode* temp = new ListNode(sum % 10);
            // 后插法建立链表
            if(head == NULL){
                head = temp;
                tail = temp;
            }
            else{
                tail->next = temp;
                tail = temp;
            }
        }
        // 试想一种情况,[5] [5] 两者相加则返回链表为 [0 1],
        // 当 5+5=10, 先返回头结点0,此时两条链表都为空,while结束。则1无法进位,所以在此有if
        // 如果是 [2] [5] 则相加为 7, 则不会产生进位,不会进入 if 
        if(sum/10 == 1){
            ListNode* temp = new ListNode(1);
            tail -> next = temp;
            tail = temp;
        }
        return head;
    }
};

总结展望

上一篇 下一篇

猜你喜欢

热点阅读