笔试题15. LeetCode OJ (2)
来源:互联网 发布:nginx 支持tcp加ssl 编辑:程序博客网 时间:2024/05/05 17:37
2. Add Two Number
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) { if(l1 == NULL && l1 == NULL) { return NULL; } if(l1 == NULL) { return l2; } if(l2 == NULL) { return l1; } bool ishead = true; int increase=0; ListNode *newHead = NULL; ListNode *cur = NULL; while(l1 && l2) { ListNode * tmp = new ListNode(l1->val+l2->val); if(increase != 0) { tmp->val+=increase; } increase = tmp->val / 10; tmp->val %= 10; if(cur != NULL) { cur->next = tmp; cur = cur->next; } if(ishead) { newHead = tmp; cur = newHead; ishead = false; } l1=l1->next; l2=l2->next; } while(l1) { cur->next = new ListNode(l1->val); cur = cur->next; if(increase != 0) { cur->val+=increase; increase = cur->val/10; cur->val%=10; } l1=l1->next; } while(l2) { cur->next = new ListNode(l2->val); cur = cur->next; if(increase != 0) { cur->val+=increase; increase = cur->val/10; cur->val%=10; } l2=l2->next; } if(increase != 0) { cur->next = new ListNode(increase); } return newHead; }};
0 0
- 笔试题15. LeetCode OJ (2)
- 笔试题2. LeetCode OJ (2) Battleships in a Board
- 笔试题14. LeetCode OJ (1)
- 笔试题16. LeetCode OJ (3)
- 笔试题17. LeetCode OJ (4)
- 笔试题18. LeetCode OJ (7)
- 笔试题19. LeetCode OJ (5)
- 笔试题20. LeetCode OJ (6)
- 笔试题21 . LeetCode OJ (8)
- 笔试题22. LeetCode OJ (9)
- 笔试题23. LeetCode OJ (10)
- 笔试题24. LeetCode OJ (11)
- 笔试题25. LeetCode OJ (12)
- 笔试题26. LeetCode OJ (13)
- 笔试题27. LeetCode OJ (14)
- 笔试题28. LeetCode OJ (15)
- 笔试题29. LeetCode OJ (16)
- 笔试题30. LeetCode OJ (17)
- LeetCode 2 - Add Two Numbers ( JAVA )
- Web前端优化最佳实践及工具集锦(如减少页面加载时间)
- 陪你走到这里了
- 基于tigase服务器的安卓客户端开发---创建聊天
- jar10
- 笔试题15. LeetCode OJ (2)
- 定义一个泛型方法
- hdoj 1434 幸福列车【模拟】
- nginx重试机制-重新发起请求导致的问题
- 序列化机制
- POJ 2488(DFS)
- 通过泛型方法返回泛型类实例
- 杭电2602-0-1背包模板题
- http常见状态码