本文共 2678 字,大约阅读时间需要 8 分钟。
题目: 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807题解:模拟竖式加法运算,从最低为开始计算,若最高位上仍存在进位,在最高位前还要进1
#include "iostream"using namespace std;#include"unordered_map"typedef struct number{ int num; struct number* next;}number;typedef struct result{ int res; struct result* next;}result;number* input(int k[3]){ number* head, * mid; number* end; head = new number; end = head; for (int i = 0;i < 3;i++) { mid = new number; mid->num = k[i]; end->next = mid; end = mid; } end->next = NULL; return head;}result* output(number *s1,number*s2){ result* head, * mid; result* end; head = new result; end = head; int carry = 0; while (s1->next!=NULL && s2->next!=NULL) { s1 = s1->next; s2 = s2->next; mid = new result; end->next = mid; end = mid; mid->res = (s1->num + s2->num+carry) % 10; //提取个位 carry = (s1->num + s2->num+carry) / 10; //存储进位 } if (carry) //判断最高位是否要继续进位 { mid = new result; end->next = mid; end = mid; mid->res = 1; } end->next = NULL; return head;}int main(){ int a[3] = { 3,2,9 }; number* a1, * a2; result* res; a1 = input(a); a2 = input(a); res = output(a1, a2); int j=0; while (res->next!=NULL) { res = res->next; if (res->next == NULL) { cout << res->res; j++; continue; } if(!(j==0&&res->res==0)) { cout << res->res << "->"; } j++; } }
题解:如果是按照顺序的方式存储(其实是我第一次看错题目了。。)创建链表number存储加数的每一位,存储完成后将两加数相加,然后再用链表result存储结果的每一位
typedef struct number{ int num; struct number* next;}number;typedef struct result{ int res; struct result* next;}result;number* input(int k[3]){ number* head, * mid; number* end; head = new number; end = head; for (int i = 0;i < 3;i++) { mid = new number; mid->num = k[i]; end->next = mid; end = mid; } end->next = NULL; return head;}result* output(number *s1,number*s2){ result* head, * mid; result* end; head = new result; end = head; int sum[4]; for (int i = 0;i < 3;i++) { s1 = s1->next; s2 = s2->next; sum[i] = (s1->num + s2->num)*pow(10,2-i); } sum[3] = sum[0] + sum[1] + sum[2]; for (int i = 0;i < 4;i++) { int k; k = sum[3] / (pow(10, 3 - i)); mid = new result; mid->res = k%10; end->next = mid; end = mid; } end->next = NULL; return head;}int main(){ int a[3] = { 9,2,3 }; number* a1, * a2; result* res; a1 = input(a); a2 = input(a); res = output(a1, a2); int j=0; while (res->next != NULL) { res = res->next; if (res->next == NULL) { cout << res->res; j++; continue; } if(!(j==0&&res->res==0)) { cout << res->res << "->"; } j++; } }
转载地址:http://mssl.baihongyu.com/