题意:
You are given two linked lists representing two non-negative numbers. The digits are stored in reverse
order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
比如:
数字3 4 2 +
数字4 6 5 =
数字8 0 7
#include <stdlib.h>
#include <stdio.h>
typedef struct _LinkNode
{
int data;
struct _LinKNode *next;
}LinkNode;
typedef struct _Linklist
{
LinkNode *head;
int length;
}Linklist;
typedef struct _Student
{
int id;
}Student;
//初始化
Linklist* Init()
{
Linklist *list=(Linklist*)malloc(sizeof(Linklist));
LinkNode *node=(LinkNode*)malloc(sizeof(LinkNode));
list->length=0;
list->head=node;
node->next=NULL;
return list;
}
//插入
void Push(Linklist* list,int pos,int data)
{
//合法性检验
if(list==NULL||pos<0)
return;
if(pos > list->length)
pos=list->length;
//创建辅助接点
LinkNode *pCurrent=list->head;
//创建新节点
LinkNode *newnode=(LinkNode*)malloc(sizeof(LinkNode));
newnode->data=data;
//遍历找到插入节点的位置
int i;
for( i=0;i<pos;i++)
pCurrent=pCurrent->next;
//插入新节点
newnode->next=pCurrent->next;
pCurrent->next=newnode;
list->length++;
}
void Print(Linklist *list)
{
LinkNode *pCurrent;
//合法性检验
if(list==NULL)
return;
//创建辅助接点
pCurrent=list->head->next;
int i;
//遍历打印
for( i=0;i<list->length;i++)
{
printf("%2d",pCurrent->data);
pCurrent=pCurrent->next;
}
}
void Add(Linklist *s1,Linklist *s2,Linklist *s3)
{
if(s1==NULL && s2==NULL)
//创建辅助节点
LinkNode *pCurrent1;
pCurrent1=s1->head->next;
LinkNode *pCurrent2;
pCurrent2=s2->head->next;
//c为进位,sum为两数相加的和,data为除去进位的数
int c=0;
int sum=0;
int data=0;
while(pCurrent1!=NULL&&pCurrent2!=NULL)
{
sum=pCurrent1->data+pCurrent2->data+c;
c=sum/10;
data=sum%10;
Push(s3,s3->length,data);
pCurrent1=pCurrent1->next;
pCurrent2=pCurrent2->next;
}
//head->1->2->3->NULL head->2->3->NULL
while(pCurrent1!=NULL)
{
sum=pCurrent1->data+c;
c=sum/10;
data=sum%10;
Push(s3,s3->length,data);
pCurrent1=pCurrent1->next;
}
//head->1->2->NULL head->1->2->3->NULL
while(pCurrent2!=NULL)
{
sum=pCurrent2->data+c;
c=sum/10;
data=sum%10;
Push(s3,s3->length,data);
pCurrent2=pCurrent2->next;
}
//head->4->2->9->NULL head->1->2->3->NULL
if(c>0)
{
Push(s3,s3->length,c);
}
}
int main()
{
//创建链表初始化
Linklist *list1=Init();
Linklist *list2=Init();
//插入数据
Push(list1,0,3);
Push(list1,0,4);
Push(list1,0,2);
Push(list2,0,4);
Push(list2,0,6);
Push(list2,0,9);
Push(list2,0,7);
Push(list2,0,5);
//打印
Print(list1);
printf("\n");
Print(list2);
//两链表相加
Linklist *list3=Init();
Add(list1,list2,list3);
//打印
printf("\n");
Print(list3);
return 0;
}