leetcode 4ADD TWO NUMBERS
来源:互联网 发布:网络借贷宝怎么还款啊 编辑:程序博客网 时间:2024/05/19 02:28
Youare given two linked lists representing two non-negative numbers. The digitsare stored in reverse order and each of their nodes contain a single digit. Addthe two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
C++ 有头结点版
/** * 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 rootNode(0); ListNode *pCurNode = &rootNode; int v1,v2,sum; int forward = 0; while(l1||l2) { v1 = (l1 ? l1->val : 0); v2 = (l2 ? l2->val : 0); sum = v1 + v2 + forward; forward = sum / 10; sum = sum % 10; ListNode *pNode = new ListNode(sum); pCurNode->next = pNode; pCurNode = pNode; if(l1) l1 = l1->next; if(l2) l2 = l2 ->next; } if(forward > 0) { ListNode *pNode = new ListNode(forward); pCurNode->next = pNode; } return rootNode.next; }};
C++ 无头结点版
/** * 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 v1 = (l1 ? l1->val : 0); int v2 = (l2 ? l2->val : 0); int sum = v1 + v2;ListNode *pCurNode =new ListNode(sum%10);ListNode *p=pCurNode;int forward = sum/10;if(l1) l1 = l1->next; if(l2) l2 = l2 ->next; while(l1||l2) { v1 = (l1 ? l1->val : 0); v2 = (l2 ? l2->val : 0); sum = v1 + v2 + forward; forward = sum / 10; sum = sum % 10; ListNode *pNode = new ListNode(sum); pCurNode->next = pNode; pCurNode = pNode; if(l1) l1 = l1->next; if(l2) l2 = l2 ->next; } if(forward > 0) { ListNode *pNode = new ListNode(forward); pCurNode->next = pNode; } return p; }};
0 0
- leetcode 4ADD TWO NUMBERS
- Leetcode【4】:Add Two Numbers
- [leetcode 4] Add Two Numbers
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- LeetCode-Add Two Numbers
- [leetcode] Add Two Numbers
- [LeetCode] Add Two Numbers
- android通过jni调用C代码socket出错问题
- Arrays类常用方法
- 云计算和openstack
- 网页全屏代码
- linux挂载分区
- leetcode 4ADD TWO NUMBERS
- PHP模板学习--Smarty 自定义函数
- TCP/IP三次握手和四次挥手
- Cocos2dx 日志小工具(更新)
- 5秒钟内反映过来的就是高手
- Dom解析操作源代码
- poj2352 Stars (树状数组)
- poj 2524(简单dfs(慢了点2000+ms过了))
- 关于福建视通(视通时代)内幕