LintCode 第167题目 链表求和
2017-12-04 15:01
387 查看
题目描述:
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中
样例
给出两个链表
基本思路:
1.首先creatLink函数创建两个单链表,每个节点的value装的是各个值,在cin输入情况输入你想要的值。
2.接着再returnLinkNodeValueCount中遍历单链表,把单链表各个节点的值逆序拼接成一个整数。
3.在creatLinkAccodingToInterger函数中传入参数,参数是步骤2中两个单链表逆序拼接成两个整数的和,然后把整数各个位置的数字再拆分成一个单链表来存储。
4.函数printValueInLink打印步骤3中的单链表各个节点value值,即得到结果。
代码实现:
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中
相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例
给出两个链表
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; }
相关文章推荐
- lintcode,167,链表求和
- [LintCode]链表求和
- lintcode-链表求和
- 167. 链表求和(add-two-numbers)(c++)----lintcode面试题之链表
- 链表求和 II-LintCode
- lintcode-链表求和
- LintCode【简单】167. 链表求和 。代码及思路
- 链表求和(LintCode)
- lintcode-167-链表求和
- 链表求和-LintCode
- LintCode-[中等] 221. 链表求和 II
- LintCode 链表求和
- LintCode | 167. 链表求和
- python_lintcode_167链表求和
- lintcode-221-链表求和 II
- lintcode ----链表求和
- lintcode(221)链表求和 II
- LintCode_167_链表求和
- LintCode_167_链表求和
- [Lintcode] #167 链表求和