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
- leetcode(2)_Add Two Numbers
- LeetCode 2_Add Two Numbers
- LeetCode 2_Add Two Numbers
- 【LeetCode】2_Add Two Numbers
- LeetCode之2_Add Two Numbers
- 2_Add Two Numbers
- leetcode第一刷_Add Two Numbers
- Leetcode第二题_Add Two Numbers
- 0002_Add Two Numbers
- 2_Add Two Number
- LeetCode 2 - Add Two Numbers
- LeetCode 2: Add Two Numbers
- Leetcode: Add Two Numbers (2)
- [leetcode 2] Add Two Numbers
- [Leetcode] 2 - Add Two Numbers
- LeetCode 2:《Add Two Numbers》
- LeetCode | #2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- b树的c++实现
- 杭电ACM 2015:偶数求和
- 定制Eclipse的Content assist(代码补全),比如空格键 "="键不上屏
- 读书笔记:《参与感-小米口碑内部营销手册》
- 验证码
- leetcode(2)_Add Two Numbers
- PHP中逗号和点号的区别
- 正则表达式
- poj 3278
- c++运算符重载
- 嘛,开通博客了。
- 没错又是感慨
- day 028 qq输入框加载FaceView
- 黑马程序员_面向对象