荣誉版主
- 积分
- -2403
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2010-5-4
- 最后登录
- 1970-1-1
|
当然是用递归,不过程序写出来需要一些小技巧地:
- struct NODE
- {
- int nVal;
- NODE* pNext;
- NODE(int n) : nVal(n), pNext(NULL) {}
- };
- int GetLen(NODE* pHead)
- {
- int nRet = 0;
- while (NULL != pHead)
- {
- nRet++;
- pHead = pHead->pNext;
- }
- return nRet;
- }
- NODE* CalcAdd(NODE* p1, int n, NODE* p2, int m)
- {
- if (0 == n || 0 == m)
- return NULL;
- NODE* pNode = NULL;
- NODE* pRet = NULL;
- if (m != n)
- {
- if (n > m)
- {
- pRet = CalcAdd(p1->pNext, n-1, p2, m);
- pNode = new NODE(p1->nVal);
- }
- else
- {
- pRet = CalcAdd(p1, n, p2->pNext, m-1);
- pNode = new NODE(p2->nVal);
- }
- }
- else
- {
- pRet = CalcAdd(p1->pNext, n-1, p2->pNext, m-1);
- pNode = new NODE(p1->nVal + p2->nVal);
- }
- if (pRet != NULL && pRet->nVal >= 10)
- {
- pRet->nVal = pRet->nVal%10;
- pNode->nVal++;
- }
- pNode->pNext = pRet;
- return pNode;
- }
- NODE* AddLnk(NODE* p1, NODE* p2)
- {
- assert(p1 && p2);
- NODE* pHead = CalcAdd(p1, GetLen(p1), p2, GetLen(p2));
- if (pHead->nVal >= 10)
- {
- NODE* pTmp = pHead;
- pHead = new NODE(1);
- pTmp->nVal = pTmp->nVal%10;
- pHead->pNext = pTmp;
- }
- return pHead;
- }
复制代码 |
|