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

     /**
     * 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) {
            if(l2==NULL) return l1;
            if(l1==NULL) return l2;
                
            struct ListNode * head=NULL;
            
            //copy l1
            struct ListNode * current=NULL;
            while(l1!=NULL)
            {
                struct ListNode * newNode=new struct ListNode(l1->val);
                if(head==NULL)
                    head=newNode;
                else
                    current->next=newNode;
                current=newNode;
                l1=l1->next;
            }
            //add
            struct ListNode * p1=head;
            struct ListNode * p2=l2;
            int add=0;
            while(true)
            {
                int sum;
                if(p2!=NULL)
                    sum=p1->val+p2->val+add;
                else
                    sum=p1->val+add;
                p1->val=sum>=10?sum-10:sum;
                add=sum>=10?1:0;
                
                if(p1->next==NULL && p2==NULL && add==0)
                    break;
                if(p1->next==NULL && p2!=NULL && p2->next==NULL && add==0)
                    break;
                    
                if(p1->next==NULL)
                    p1->next=new struct ListNode(0);
                p1=p1->next;
                if(p2!=NULL) 
                    p2=p2->next;
            }
         
            return head;
        }
    };
  • 相关阅读:
    java线程池实践
    JAVA中间件(middleware)模式
    [开源]制作docker镜像不依赖linux和Docker环境
    利用浏览器favicon的缓存机制(F-Cache)生成客户端浏览器唯一指纹
    Docker镜像构建原理解析(不装docker也能构建镜像)
    ORM框架对分表分库之分库和分表指定不同的字段
    volatile的内存屏障的坑
    go和python的比较,获取当前时间是今年第几个星期
    c++学生管理系统
    c++学生管理系统(三)
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759169.html
Copyright © 2011-2022 走看看