题目描述:给定两个链表,逆序表示两个整数,对这两个链表进行求和。
思路:注意进位即可,可以就地操作,但是实现稍微麻烦一点(如果不就地的话,可以转化成递归操作,代码更加简洁)
1 #include <iostream> 2 #include <string> 3 #include <fstream> 4 #include <map> 5 #include <algorithm> 6 #include <vector> 7 #include <ctime> 8 #include <bitset> 9 10 using namespace std; 11 12 template<typename T> 13 class Node 14 { 15 public: 16 Node<T> *next; 17 T data; 18 19 Node(T d):data(d),next(NULL){} 20 void appendToTail(T d) 21 { 22 Node<T> *end = new Node<T>(d); 23 Node<T> *n = this; 24 while(n->next != NULL) 25 { 26 n = n->next; 27 } 28 n->next = end; 29 } 30 }; 31 32 int main() 33 { 34 Node<int> *head1 = new Node<int>(7); 35 head1->appendToTail(1); 36 head1->appendToTail(6); 37 Node<int> *head2 = new Node<int>(5); 38 head2->appendToTail(9); 39 head2->appendToTail(2); 40 //2.4 41 int c = 0; 42 Node<int> *resHead = NULL; 43 if(head1 == NULL) 44 { 45 resHead = head1; 46 } 47 else if(head2 == NULL) 48 { 49 resHead = head2; 50 } 51 else 52 { 53 resHead = head1; 54 Node<int> *restmp = head1; 55 while(head1 != NULL && head2 != NULL) 56 { 57 int tmp1 = head1->data; 58 int tmp2 = head2->data; 59 restmp->data = (tmp1+tmp2+c)%10; 60 c = (tmp1+tmp2)/10; 61 head1 = head1->next; 62 head2 = head2->next; 63 if(head1 != NULL) 64 { 65 restmp = restmp->next; 66 } 67 else 68 { 69 restmp->next = head2; 70 if(head2 != NULL) 71 restmp = restmp->next; 72 } 73 } 74 while(head1 != NULL) 75 { 76 int tmp1 = head1->data; 77 restmp->data = (tmp1+c)%10; 78 c = (head1->data+c)/10; 79 head1 = head1->next; 80 if(restmp->next != NULL) 81 restmp = restmp->next; 82 } 83 while(head2 != NULL) 84 { 85 int tmp2 = head2->data; 86 restmp->data = (tmp2+c)%10; 87 c = (tmp2+c)/10; 88 head2 = head2->next; 89 if(restmp->next != NULL) 90 restmp = restmp->next; 91 } 92 if(c != 0) 93 restmp->next = new Node<int>(c); 94 } 95 while(resHead != NULL) 96 { 97 cout<<resHead->data<<endl; 98 resHead = resHead->next; 99 } 100 return 0; 101 }