2-m-Add Two Numbers
2015-05-05 21:59
120 查看
还算简单的medium级别题,主要注意逢10进位的问题,以及循环内判断node是否已到尾端的情况。
代码如下:
代码如下:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode *result = (struct ListNode *)malloc(sizeof(struct ListNode)); struct ListNode *node = result; struct ListNode *l1p = l1, *l2p = l2; bool isTenth = false; while (l1p || l2p) { if (!l1p) node->val = l2p->val; else if (!l2p) node->val = l1p->val; else node->val = l1p->val + l2p->val; if (isTenth) node->val++; if (node->val >= 10) { isTenth = true; node->val -= 10; } else isTenth = false; if (l1p) l1p = l1p->next; if (l2p) l2p = l2p->next; if (l1p != NULL || l2p != NULL) { node->next = (struct ListNode *)malloc(sizeof(struct ListNode)); node = node->next; } } node->next = NULL; if (isTenth) { node->next = (struct ListNode *)malloc(sizeof(struct ListNode)); node->next->val = 1; node->next->next = NULL; } return result; }
相关文章推荐
- LeetCode第四题,Add Two Numbers
- 2. Add Two Numbers
- LeetCode 2. Add Two Numbers 题解
- Leetcode 2. Add Two Numbers The Solution of Python and Javascript
- Add Two Numbers
- Add Two Numbers
- leetcode - Add Two Numbers
- [Leetcode] Add Two Numbers
- leetcode 2. Add Two Numbers
- Add Two Numbers
- LeetCode (2)Add Two Numbers
- Add Two Numbers leetcode
- leetcode--Add two numbers
- Add Two Numbers
- Leetcode : Add Two Numbers
- LeetCode 2 Add Two Numbers
- leetcode 练习题 -- 2. Add Two Numbers
- Leetcode 2-Add two numbers
- Populating Next Right Pointers in Each Node I,II,Add Two Numbers,Integer to Roman
- 2.Add Two Numbers