2. 两数相加(原题网址)
//2. 两数相加
//给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
//请你将两个数相加,并以相同形式返回一个表示和的链表。
//
//你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
//
//
//示例 1:
//
//输入:l1 = [2,4,3], l2 = [5,6,4]
//输出:[7,0,8]
//解释:342 + 465 = 807.
#include<stdio.h>
#include<stdlib.h>
typedef struct listNode{
int val;
struct listNode * next;
}ListTab;
//ListTab * numCreate(int *nums,int numsLength);
ListTab * intCreate(int nums);
ListTab * getSumLIst(ListTab *nodeA,ListTab *nodeB);
int listToInt(ListTab *node);
void nodePrintf(ListTab *node);
int main(int argc, const char * argv[]) {
// insert code here...
ListTab *nodeA=NULL;
ListTab *nodeB=NULL;
ListTab *nodeSum=NULL;
int a=0,b=0;
scanf("%d %d",&a,&b);
nodeA=intCreate(a);
nodeB=intCreate(b);
nodeSum=getSumLIst(nodeA, nodeB);
printf("%d\t%d\t%d\n",a,b,a+b);
printf("%d\t%d\t%d\n",listToInt(nodeA),listToInt(nodeB),listToInt(nodeSum));
nodePrintf(nodeA);
nodePrintf(nodeB);
nodePrintf(nodeSum);
printf("\n");
return 0;
}
ListTab * intCreate(int nums){
ListTab *head=NULL;
ListTab *node=NULL;
ListTab *end=NULL;
head=(ListTab*)malloc(sizeof(ListTab));
end=head;
int n=0,result=0;
n=nums;
result=n%10;
head->val=result;
n=n/10;
while (n!=0) {
result=n%10;
node=(ListTab*)malloc(sizeof(ListTab));
node->val=result;
node->next=NULL;
end->next=node;
end=node;
n=n/10;
}
end->next=NULL;
return head;
}
ListTab * getSumLIst(ListTab *nodeA,ListTab *nodeB){
ListTab *head=NULL;
int tmpIA=0,tmpIB=0;
tmpIA=listToInt(nodeA);
tmpIB=listToInt(nodeB);
head=intCreate(tmpIA+tmpIB);
return head;
}
int listToInt(ListTab *node){
int val=0;
int digit =1;
ListTab *loop=node;
while (loop) {
val+=(loop->val)*digit;
loop=loop->next;
digit*=10;
}
return val;
}
void nodePrintf(ListTab *node){
ListTab *loop=NULL;
loop=node;
while (loop) {
printf("%d",loop->val);
loop=loop->next;
}
printf("\t");
}