• 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;
        }
  • 相关阅读:
    MVC3分页传2参
    C# 二进制存储图片到mssql(一)
    著名黑客组织[转]
    浅看C# md5加密
    google搜索技巧
    字符串编码转换 GBK utf8
    objectivec 中随机数的用法 (3种:arc4random() 、random()、CCRANDOM_0_1() )
    NSPredicate的用法
    Java关键字final、static使用总结()
    CGAffineTransform相关函数
  • 原文地址:https://www.cnblogs.com/louwqtc/p/AddTwoNumbers.html
Copyright © 2020-2023  润新知