leetcode(2)_Add Two Numbers

来源:互联网 发布:淘宝如何提高搜索排名 编辑:程序博客网 时间:2024/06/06 15:59

【题目】

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

【答案】

/************************************************************************** 文件: add_two_num.c* 作者: fantasy* 邮箱: fantasy@gmail.com * 创建时间: 2015年05月03日 星期日 22时08分38秒*************************************************************************/#include <stdio.h>#include <stdlib.h>/** * Definition for singly-linked list. */struct ListNode {int val;struct ListNode *next;};struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {    struct ListNode* result = NULL;struct ListNode* tmp = NULL;struct ListNode* node = NULL;int remainder = 0;while (l1 != NULL){node = (struct ListNode*)malloc(sizeof(struct ListNode));node->val = (l1->val + l2->val + remainder) % 10 ;remainder = (l1->val + l2->val + remainder) / 10; node->next = NULL;if (result == NULL){result = node;tmp = node;}else{tmp->next = node;tmp = node;}l1 = l1->next;l2 = l2->next;}if (0 != remainder){node = (struct ListNode*)malloc(sizeof(struct ListNode));node->val = remainder;remainder = 0;node->next = NULL;tmp->next = node;tmp = node;}return result;}struct ListNode* create_Lists(int arr[], int arr_len){int i = 0;struct ListNode *l = NULL;struct ListNode *tmp = NULL;struct ListNode *node = NULL;for (i = 0; i < arr_len; i++){node = (struct ListNode*)malloc(sizeof(struct ListNode));node->val = arr[i];node->next = NULL;if (NULL == l){l = node;tmp = node;}else{tmp->next = node;tmp = node;}}return l;}int main(){struct ListNode *l1;struct ListNode *l2;struct ListNode *results;int in1[] = {2, 4, 3};int in2[] = {5, 6, 4};l1 = create_Lists(in1, sizeof(in1)/sizeof(in1[0]));l2 = create_Lists(in2, sizeof(in2)/sizeof(in2[0]));results = addTwoNumbers(l1, l2);while (results != NULL){printf("%d", results->val);results = results->next;if (NULL != results){printf("->");}else{printf("\n");}}return 0;}


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 发货单号填错了怎么办 发快递忘了单号怎么办 国际物流查不到物流怎么办 纸币上印邪教该怎么办 钥匙掉到电梯缝里怎么办 汽车电子钥匙铜线折一根怎么办 防盗门的锁不好开怎么办 同学帮刷饭卡说不用还钱了怎么办 em231电源指示灯不亮怎么办 运行广联达卡住怎么办 马桶被粪便(大便)堵了怎么办 子宫壁厚12mm怎么办 管子太多每次洗澡都是冷水怎么办 热水冷水装反了怎么办 大树被高锰酸钾灌溉了怎么办会死吗 防盗门门被锁了怎么办 门被里面反锁了怎么办 门里面被锁了怎么办 被锁在门里怎么办 门锁住了没钥匙怎么办 车被别人锁住了怎么办 汽车轱辘被锁了怎么办 小车轮胎被锁了怎么办 国防光缆无明显标识被挖断怎么办 临工210挖掘机柴油进气怎么办 汽车抛光蜡干了怎么办 洗碗铁丝球吃了怎么办 牙套铁丝吃肚子怎么办 小铁丝吃到肚子怎么办 绿色抛光膏干了怎么办 不锈钢被盐酸弄黑了怎么办 不锈钢被草酸洗了怎么办 不锈钢洗菜盆被草酸腐蚀了怎么办 汽油发电机加了柴油怎么办 装载机发动机加入齿轮油怎么办 印尼的FromE错了怎么办 寄快递被弄坏了怎么办 福田口岸手表被扣怎么办? 网页显示与服务器连接失败怎么办 唯品会中发货无法清关怎么办 国际快递被海关扣了怎么办