单链表大整数加法

时间:2023-01-25 19:44:04

单链表大整数加法,节点是char型。

First     List:   head->1->8->9

Second List:   head->9->8->1

Result  List:    head->1->1->7->0

实现了单链表(单链表类模板),现在使用单链表实现大整数加法

 1 #include "stdafx.h"
 2 #include "SingleList.h"
 3 #include <string.h>
 4 class BigDataList{
 5 public:
 6     BigDataList(){
 7     }
 8 public:
 9     SingleList<char>* add(SingleList<char> &l1, SingleList<char> &l2);
10 };
11 SingleList<char>* BigDataList::add(SingleList<char> &l1 , SingleList<char> &l2){
12     l1.ReverseSinglyLinkedList();
13     l2.ReverseSinglyLinkedList();
14     SingleList<char> *l3=new SingleList<char>;
15     int length1 = l1.length();
16     int length2 = l2.length();
17     int ceil = 0 ;
18     int mod = 0;
19     int i = 0;
20     if(length2==length1){
21         for(;i <length1 && i < length2 ; i++){
22             mod = ((l1.get(i)-'0')+((l2.get(i)-'0'))+ceil)%10;
23             ceil = ((l1.get(i)-'0')+((l2.get(i)-'0'))+ceil)/10;
24             l3->insert('0'+mod,i);
25         }
26         if(ceil>0){
27             l3->insert(ceil+'0',i);
28         }
29     }
30     else if(length1>length2){
31         for(; i<length2 ; i++){
32             mod = ((l1.get(i)-'0')+((l2.get(i)-'0'))+ceil)%10;
33             ceil = ((l1.get(i)-'0')+((l2.get(i)-'0'))+ceil)/10;
34             l3->insert('0'+mod,i);
35         }
36         for(;i<length1;i++){
37             mod = ((l1.get(i)-'0')+ceil)%10;
38             ceil = ((l1.get(i)-'0')+ceil)/10;
39             l3->insert('0'+mod,i);
40         }
41         if(ceil>0){
42             l3->insert(ceil+'0',i);
43         }
44     }
45     else{
46         for(; i<length1 ; i++){
47             mod = ((l1.get(i)-'0')+((l2.get(i)-'0'))+ceil)%10;
48             ceil = ((l1.get(i)-'0')+((l2.get(i)-'0'))+ceil)/10;
49             l3->insert('0'+mod,i);
50         }
51         for(;i<length2;i++){
52             mod = ((l2.get(i)-'0')+ceil)%10;
53             ceil = ((l2.get(i)-'0')+ceil)/10;
54             l3->insert('0'+mod,i);
55         }
56         if(ceil>0){
57             l3->insert(ceil+'0',i);
58         }
59     }
60     l3->ReverseSinglyLinkedList();
61     l3->print();
62 
63     return l3;
64 }