您的位置:首页 > 其它

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: