zoukankan      html  css  js  c++  java
  • 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

    Code:

    class Solution {
    public:
        ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
            ListNode *start= new ListNode(0);
            start->next=l1; 
            while(l1||l2){
                if(l1&&l2){
                    l1->val=l1->val+l2->val;
                    if(l1->val>9){
                        l1->val=l1->val%10;
                        if(l1->next)
                            l1->next->val=l1->next->val+1;
                        else if(l2->next){
                            l1->next=l2->next;
                            l2->next->val=l2->next->val+1;
                            l2=NULL;
                        }else{
                            ListNode *carry= new ListNode(1);
                            l1->next=carry;
                        }   
                    }
                    if(!l1->next&&l2->next){
                        l1->next=l2->next;
                        l2=NULL;
                    }
                    l1=l1->next;
                    if(l2)
                        l2=l2->next;
                }else if(l1){
                    if(l1->val>9){
                        l1->val=l1->val%10;
                        if(l1->next)
                            l1->next->val=l1->next->val+1;
                        else{
                            ListNode *carry= new ListNode(1);
                            l1->next=carry;
                        }
                    }
                    l1=l1->next;
                }
            }
            l1=start->next;
            delete start;
            return l1;
        }
    };
  • 相关阅读:
    truncate table
    SSIS学习笔记
    Bing Developer Assistant开发随记
    数组中的逆序对
    第一个只出现一次的字符
    丑数
    把数组排成最小的数
    连续子数组的最大和
    最小的k个数
    数组中出现次数超过一半的数字
  • 原文地址:https://www.cnblogs.com/winscoder/p/3409737.html
Copyright © 2011-2022 走看看