题目
题解
实际上就是要考察两个链表每个元素相加的问题。需要解决3个问题:
- 如何创建链表?
- 如何处理两链表长度不一致问题?
- 如何处理进位?注意最后一位的进位
链表相关知识回忆
学的数据结构的东西都忘光光了.......现在回忆一下:
创建链表:要先定义头节点,然后申请空间给头结点,此后申请多个node,让头结点指向node。
#include<stdio.h>
#include<stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *create(int n){
struct ListNode *head,*node,*end;
head = (struct ListNode *)malloc(sizeof(struct ListNode)); //给头节点申请内存
end = head; //若是空表,则头尾地址一致
for(int i=0;i<n;i++){ //利用for循环向链表中添加数据
node = (struct Stu *)malloc(sizeof(struct Stu));//给普通节点申请内存空间
scanf("%d",&node->val);
end->next = node; //让上一个节点的数据域指向当前节点
end = node; //end指向当前节点,最终end指向尾节点
}
end->next = NULL; //给end的指针域置空
return head; //返回头节点的地址
}
题目完整代码:
注意两链表的长度不同,就基于最长的那个,短的那个以0代替
#include<stdio.h>
#include<stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
struct ListNode*l3,*end,*node;
int jin=0;
l3=(struct ListNode *)malloc(sizeof(struct ListNode));
end=l3;
int temp;
while(l2||l1)
{
int n1,n2;
n1=l1? l1->val : 0; //注意不同长度的链表以0来替代
n2=l2? l2->val : 0;
temp=(n1+n2+jin)%10;
jin=(n1+n2+jin)/10;
node=(struct ListNode *)malloc(sizeof(struct ListNode));
node->val=temp;
end->next=node;
end=node;
if(l1) //注意这里的条件
{
l1=l1->next;
}
if(l2)
{
l2=l2->next;
}
if(jin>0)
{
node=(struct ListNode *)malloc(sizeof(struct ListNode));
node->val=jin;
end->next=node;
end=node;
}
end->next=NULL;
l3=l3->next;
return l3;
}
int main()
{
int n1,n2;
scanf("%d%d",&n1,&n2);
struct ListNode*l1,*l2,*node,*end1,*end2,*l3;
l1=(ListNode*)malloc(sizeof(ListNode));
l2=(ListNode*)malloc(sizeof(ListNode));
end1=l1,end2=l2;
int i=0;
for(i=0;i<n1;i++)
{
node=(ListNode*)malloc(sizeof(ListNode));
scanf("%d",&node->val);
end1->next=node;
end1=node;
}
end1->next=NULL;
for(i=0;i<n2;i++)
{
node=(ListNode*)malloc(sizeof(ListNode));
scanf("%d",&node->val);
end2->next=node;
end2=node;
//printf("test:%d\n",node->val);
}
end2->next=NULL;
l1=l1->next,l2=l2->next;
l3=addTwoNumbers(l1,l2);
while(l3)
{
printf("%d ",l3->val);
l3=l3->next;
}
}
做这道题的时候,由于对创建链表的东西不熟悉所以犯了错误,把循环条件while(l1||l2)写成了while(l1->next!=NULL||l2->next!=NULL)导致最后一个节点的值没有参与计算。
本题收获最大的是对链表长度不一样怎么处理:以最长的为基准,不够长的部分用0代替。