链表相加
链表相加:
给定两个链表,分别表示两个非负整数。它们的数字逆序存储在链表中,且每个结点中存储一个数字,计算两个数的和,并且返回和的链表头指针。
如:输入:2->4->3,5->6->4.
输出:7->0->8.
程序实现:
1 /************************************ 2 File Name:ListAdd.cpp 3 Author: godfrey 4 Created Time: 2016/04/28 5 *************************************/ 6 #include <iostream> 7 #include <cstdio> 8 #include <cstdlib> 9 using namespace std; 10 11 typedef struct tagSNode{ 12 int value; 13 tagSNode* pNext; 14 15 tagSNode(int v):value(v),pNext(NULL) {} 16 }SNode; 17 //打印链表 18 void Print(SNode* pHead){ 19 SNode* p = pHead->pNext; 20 while(p){ 21 cout<<p->value<<" "; 22 p = p->pNext; 23 } 24 cout<<endl; 25 } 26 //删除分配结点空间 27 void Destroy(SNode* pHead){ 28 SNode* p = pHead->pNext; 29 while(p){ 30 pHead->pNext = p->pNext;//与头插法相反 31 delete p; 32 p = pHead->pNext; 33 } 34 delete pHead; 35 } 36 //链表相加 37 SNode* ListAdd(SNode* pHead1,SNode* pHead2){ 38 SNode* pSum = new SNode(0); 39 SNode* pTail = pSum;//新结点插入pTail的后面 40 SNode* p1 = pHead1->pNext; 41 SNode* p2 = pHead2->pNext; 42 SNode* pCur = NULL; 43 int carry = 0;//进位 44 int value; 45 //处理两者都存在的加法 46 while(p1&&p2){ 47 value = p1->value + p2->value +carry; 48 carry = value / 10; 49 value %= 10; 50 pCur = new SNode(value); 51 pTail->pNext = pCur; 52 pTail = pCur; 53 54 p1 = p1->pNext; 55 p2 = p2->pNext; 56 } 57 //处理长的链表 58 SNode* p = p1 ? p1 : p2; 59 while(p){ 60 value = p->value +carry; 61 carry = value / 10; 62 value %= 10; 63 pCur = new SNode(value); 64 pTail->pNext = pCur; 65 pTail = pCur; 66 67 p = p->pNext; 68 } 69 //处理可能存在的进位 70 if(carry!=0){ 71 pTail->pNext = new SNode(carry); 72 } 73 74 return pSum; 75 } 76 77 int main() 78 { 79 SNode* pHead1 = new SNode(0); 80 for(int i=0;i<6;i++){ 81 SNode* p = new SNode(rand()%10); 82 p->pNext = pHead1->pNext; 83 pHead1->pNext = p; 84 } 85 86 SNode* pHead2 = new SNode(0); 87 for(int i=0;i<9;i++){ 88 SNode* p = new SNode(rand()%10); 89 p->pNext = pHead2->pNext; 90 pHead2->pNext = p; 91 } 92 Print(pHead1); 93 Print(pHead2); 94 SNode* pSum = ListAdd(pHead1,pHead2); 95 Print(pSum); 96 Destroy(pHead1); 97 Destroy(pHead2); 98 Destroy(pSum); 99 return 0; 100 }
运行结果:
转载请注明出处:
C++博客园:godfrey_88
http://www.cnblogs.com/gaobaoru-articles/
posted on 2016-04-28 14:51 Brainer-Gao 阅读(230) 评论(0) 编辑 收藏 举报