002Add Two Numbers
来源:互联网 发布:2017成都软件行业 编辑:程序博客网 时间:2024/06/04 19:10
002Add Two Numbers
目录
- 002Add Two Numbers
- 目录
- 题目内容
- 我的代码
- 小记
- 目录
第二题比较简单,应该是最优的,只要处理好链表和地址即可,需要学习下函数中malloc和new关于内存的区别。
- malloc与new
题目内容
==
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
我的代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* tmp(0); int i; ListNode* first = (ListNode*)malloc(sizeof(ListNode)); tmp = first; int remain=0; while(l1!=NULL&&l2!=NULL) { ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode)); temp_list->val = (remain + l1->val + l2->val)%10; remain = (remain + l1->val + l2->val)/10; tmp->next = temp_list; tmp = temp_list; l1 = l1->next; l2 = l2->next; } while(l1!=NULL) { ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode)); temp_list->val = (remain + l1->val)%10; remain = (remain + l1->val)/10; tmp->next = temp_list; tmp = temp_list; l1 = l1->next; } while(l2!=NULL) { ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode)); temp_list->val = (remain + l2->val)%10; remain = (remain + l2->val)/10; tmp->next = temp_list; tmp = temp_list; l2 = l2->next; } if(remain!=0) { ListNode* temp_list = (ListNode*)malloc(sizeof(ListNode)); temp_list->val = remain; tmp->next = temp_list; tmp = temp_list; } tmp->next = NULL; return first->next; }};
小记
认真即可,想清楚具体流程。
0 0
- 002Add Two Numbers
- 002 - Add Two Numbers
- 002 Add Two Numbers
- 002Add-Two-Numbers
- 【leetcode】002 Add Two Numbers
- LeetCode 002 Add Two Numbers
- OJ 002 Add Two Numbers
- LeetCode 002-Add Two Numbers
- [LeetCode]-002-Add Two Numbers
- LeetCode #002 Add Two Numbers
- LeetCode 002, Add Two Numbers
- 002 Add Two Numbers [Leetcode]
- LeetCode 002 Add Two Numbers
- 002 Add Two Numbers [Leetcode]
- 002Add Two Numbers (C)
- LeetCode #002 Add Two Numbers
- LeetCode 002 Add Two Numbers
- leetcode-002 Add Two Numbers
- cmd自动删除当前目录及子目录中的所有空文件
- 深入分析 Docker 镜像原理
- 优秀项目经理应备技能07-项目的执行与控制
- php开启错误提示
- 不可征服
- 002Add Two Numbers
- 简易程序--读jpg到txt
- JavaScript只能输入数字和两位小数
- ubuntu1404 开发环境配置
- WebLogic连接池错误: BEA-001153
- C++ 遍历文件夹
- 瀑布流(jquery)
- datagridview控件中使用comboBox控件(datagridviewcomboboxcolumn类)
- A journey of a packet within OpenContrail