leetcode:Add Two Numbers
2015-07-15 21:37
447 查看
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
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) { int flag = 0, num1, num2; ListNode * tmp = NULL; ListNode * t = (ListNode *)malloc(sizeof(ListNode)); t->next = NULL; ListNode * p = t; while(l1 || l2) { num1 = l1 ? l1->val : 0; num2 = l2 ? l2->val : 0; if(num1 + num2 + flag >= 10) { t->val = num1 + num2 + flag - 10; flag = 1; } else { t->val = num1 + num2 + flag; flag = 0; } l1 = l1 ? l1->next : NULL; l2 = l2 ? l2->next : NULL; tmp = t; t->next = (ListNode *)malloc(sizeof(ListNode)); t->next->next = NULL; t = t->next; } if(flag) t->val = 1; else tmp->next = NULL; return p; } };
相关文章推荐
- 浏览器对象模型BOM-window对象
- “奔跑吧,牛客“---是男人就下100层
- matlab中句柄图性对像的设置
- 【转】蜗牛求职记之华为篇
- Acdream 1115——找规律——Salmon And Cat
- C++编程的一些基础小知识
- Canvas 雾玻璃
- C#中如何在程序中引用共享程序集
- java web 开发乱码总结
- 流媒体协议介绍(rtp/rtcp/rtsp/rtmp/mms/hls)
- c++命名规范
- Better ELK, 新浪实时日志分析服务进化
- Codeforces 544E Remembering Strings 状压dp
- java与c++内存泄露的问题
- C#高级编程三十九天----比较对象的相等性
- 试试博客怎么写
- Unity3d在线游戏Socket通讯
- ASP.NET MVC Overview
- 第六章、管道及IO重定向
- ZOJ 2655 Water Pipe bfs 带方向状态