• 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

      遍历两个链表,对每个节点依次相加即可,最后遍历完两个链表之后还要注意进位的值是否为0.

      c++实现:

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            int carry = 0;
            ListNode *head = NULL,*p = NULL;
            while(l1||l2){
                if(l1){
                    carry += l1->val;
                    ListNode *temp = l1;
                    l1 = l1->next;
                    free(temp);
                }
                if(l2){
                    carry += l2->val;
                    ListNode *temp = l2;
                    l2 = l2->next;
                    free(temp);
                }
                ListNode *temp = new ListNode(carry%10);
                carry /= 10;
                if(p){
                    p->next = temp;
                    p = p->next;
                }
                else{
                    head = p = temp;
                }
            }
            if(carry){
                p->next = new ListNode(carry);
            }
            return head;
        }

      java实现:

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode ret = null;
            ListNode p = null;
            int carry = 0;
            while(l1!=null||l2!=null){
                int x = 0,y = 0,sum = 0;
                if(l1!=null){
                    x = l1.val;
                    l1 = l1.next;
                }
                if(l2!=null){
                    y = l2.val;
                    l2 = l2.next;
                }
                sum = x+y+carry;
                carry = sum/10;
                ListNode temp = new ListNode(sum%10);
                if(ret==null){
                    ret = temp;
                    p = ret;
                }
                else{
                    p.next = temp;
                    p = p.next;
                }
            }
            if(carry>0){
                p.next = new ListNode(carry);
            }
            return ret;
        }
  • 相关阅读:
    微信开发 (一) 消息回复
    java文本获取
    Axis2开发webservice详解
    springmvc 统一处理异常
    easyui 动态添加input标签
    excel 导入
    eclipse启动tomcat出现内存溢出错误 java.lang.OutOfMemoryError: PermGen space
    配置阿里云SLB全站HTTPS集群
    Nginx之HTTPS
    Nginx实现rewrite重写
  • 原文地址:https://www.cnblogs.com/louwqtc/p/AddTwoNumbers.html
Copyright © 2020-2023  润新知