002Add Two Numbers
2015-08-25 13:52
218 查看
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; } };
小记
认真即可,想清楚具体流程。相关文章推荐
- [原]GitHub控件之BadgeView(类似QQ消息数字提醒)
- collectionView XibCell 注册
- 视图控制对象生命周期-init、viewDidLoad、viewWillAppear、viewDidAppear、viewWillDisappear等的区别及用途
- Git 常用命令
- Servlet中如何实现页面转发
- WIN32控件使用大全
- windows内存管理
- flexigrid
- 【linux】ubuntu 14.04下安装mysql 5.5
- cmd自动删除当前目录及子目录中的所有空文件
- MFC中CString的Format方法使用技巧
- java单例模式 Singleton
- android 为TextView添加边框
- MVC5+EF6,性能调优
- linux常用命令(查看某些软件是否已安装)
- 分布式MySQL数据库TDSQL架构分析
- SQLite和MySQL数据库的区别与应用
- 游戏任务剧情布局系统分析
- layoutSubviews总结
- Binary Tree Paths