首页 > 代码库 > LeetCode2-Add Two Numbers
LeetCode2-Add Two Numbers
题目
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
分析:
这道题并不难,主要是细节的分析和控制,一个特殊情况就是两个列都遍历完之后,但是进位为1,此时要新建一个尾节点来存储这个数。
参考代码:
/** * 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) { bool jw=0; int num=0; int sum=0; int count = 0; ListNode *result, *pre_node, *cur_node; while (l1 != NULL && l2 != NULL) { sum = l1->val + l2->val + jw; num = sum % 10; cur_node = (ListNode *)malloc(sizeof(ListNode)); cur_node->val = num; cur_node->next = NULL; if (count == 0) { result = cur_node; pre_node = cur_node; } else { pre_node->next = cur_node; pre_node=pre_node->next; } l1 = l1->next; l2 = l2->next; count++; jw=sum/10; } while (l1 != NULL) { sum = l1->val+jw; num = sum % 10; l1->val=num; cur_node->next = l1; cur_node=cur_node->next; l1 = l1->next; jw=sum/10; } while (l2 != NULL) { sum = l2->val+jw; num = sum % 10; l2->val=num; cur_node->next = l2; cur_node=cur_node->next; l2 = l2->next; jw=sum/10; } if(jw==1) { ListNode *tail=(ListNode *)malloc(sizeof(ListNode)); tail->val=jw; cur_node->next=tail; cur_node=cur_node->next; } cur_node->next = NULL; return result; }};
LeetCode2-Add Two Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。