• Add Two Numbers


    问题描述:

    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.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8


    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode* res, *L1=l1, *L2=l2, *temp;
        while (L1&&L2) {
            L1->val=L2->val=L1->val+L2->val;
            L1 = L1->next;
            L2 = L2->next;
        }
        res = (L1) ? l1 : l2;
        temp=res;
        while (temp) {
            if (temp->val>=10) {
                if (!temp->next) 
                temp->next = (struct ListNode*)calloc(1,sizeof(struct ListNode));
                temp->val-=10;
                temp->next->val+=1;
            } 
            temp = temp->next;
        }
        return res;
    }


  • 相关阅读:
    c# 中的线程和同步
    Javascript 观察者模式
    连接SQLite 创建ADO.net实体类
    给软件增加注册功能 c#
    log4net 使用步骤
    C# 操作 Excel
    PCL编译历程
    设计模式
    kinect
    eclipse配置servlet错误
  • 原文地址:https://www.cnblogs.com/chxuan/p/8232113.html
Copyright © 2020-2023  润新知