您的位置:首页 > 理论基础 > 数据结构算法

LintCode 第167题目 链表求和

2017-12-04 15:01 387 查看
题目描述:

你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中
相反
的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。

样例

给出两个链表 
3->1->5->null
 和 
5->9->2->null
,返回 
8->0->8->null


基本思路:

1.首先creatLink函数创建两个单链表,每个节点的value装的是各个值,在cin输入情况输入你想要的值。

2.接着再returnLinkNodeValueCount中遍历单链表,把单链表各个节点的值逆序拼接成一个整数。

3.在creatLinkAccodingToInterger函数中传入参数,参数是步骤2中两个单链表逆序拼接成两个整数的和,然后把整数各个位置的数字再拆分成一个单链表来存储。

4.函数printValueInLink打印步骤3中的单链表各个节点value值,即得到结果。

代码实现:

#include <iostream>
using namespace std;

typedef struct LinkNode {
int value;
LinkNode * next;
}LinkNode;

LinkNode * creatLink(int n){
LinkNode * node = NULL;
while (n!=0) {
LinkNode * tempNode = (struct LinkNode *)malloc(sizeof(struct LinkNode));
int tempValue ;
cin>>tempValue;
tempNode->value = tempValue;
tempNode->next = node;
node = tempNode;
n--;
}
return node;
}

int returnLinkNodeValueCount(LinkNode *headNode){
LinkNode * tempNode = headNode;
int tempValue = 0;
while (tempNode != NULL) {
tempValue = tempValue*10 + tempNode->value;
tempNode = tempNode->next;
}
return tempValue;
}

LinkNode * creatLinkAccodingToInteger(int n){
LinkNode * node = NULL;
while ( n!= 0) {
int residue = n%10;
LinkNode * tempNode = (struct LinkNode *)malloc(sizeof(struct LinkNode));
tempNode->value = residue;
tempNode->next = node;
node = tempNode;
n = n/10;
}
return node;
}

void printValueInLink(LinkNode *headNode) {
LinkNode * tempNode = headNode;
while (tempNode != NULL) {
cout<<tempNode->value<<"->";
tempNode = tempNode->next;
}
cout<<"Null";
}

int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";

LinkNode *AHeadNode = creatLink(3);
LinkNode *BHeadNode = creatLink(3);
int a = returnLinkNodeValueCount(AHeadNode);
int b = returnLinkNodeValueCount(BHeadNode);
printValueInLink(creatLinkAccodingToInteger(a+b));

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构与算法