一开始使用把链表里的数相加,再分配到链表中,后来发现,当链表数太大的时候,long int也会出界,无法得到数,所以选择另外的方法。
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
//创建链表
struct ListNode* creatList()
{
struct ListNode* headNode = (struct ListNode*)malloc(sizeof(struct ListNode));
//headNode 成为了结构体变量
//变量使用前必须被初始化
headNode->next = NULL;
return headNode;
}
//创建节点
struct ListNode* creatNode(int data)
{
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
//变量使用前必须被初始化
newnode->val = data;
newnode->next = NULL;
return newnode;
}
//头插法
void insertNodeByHead(struct ListNode* headNode,int data)
{
struct ListNode* newnode = creatNode(data);
newnode->next = headNode->next;
headNode->next = newnode;
}
//链表倒叙
struct ListNode* reverselist(struct ListNode* headNode)
{
struct ListNode* pre;
struct ListNode* cur;
struct ListNode* nex;
pre = NULL;
cur = headNode;
nex = headNode;
while(cur!=NULL)
{
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
return pre;
}
//主程序
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
head1 = reverselist(head1); //链表倒序
head2 = reverselist(head2);
struct ListNode* list = creatList();
struct ListNode* p1;
struct ListNode* p2;
p1 = head1;
p2 = head2;
int num1=0; //对10取余--->个位
int num2=0; //对10取整--->十位
int i,j;
while(p1!=NULL || p2!=NULL)
{
if(p1==NULL)
{
i=0;
}
else
{
i = p1->val;
p1=p1->next;
}
if(p2==NULL)
{
j=0;
}
else
{
j = p2->val;
p2=p2->next;
}
num1 = (i+j+num2)%10;
insertNodeByHead(list,num1);
num2 = (i+j+num2)/10;
}
if(num2>0)
{
insertNodeByHead(list,num2);
}
return list->next;
}