项目场景
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
提示:
每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/add-two-numbers
问题描述及解决
1. 堆区结构体变量
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
//结构体类型的定义
struct stu
{
char name[50];
int age;
};
int main()
{
struct stu *p = NULL;
p = (struct stu *)malloc(sizeof(struct stu)); //申请内存的方式
//如果是指针变量,通过->操作结构体成员
strcpy(p->name, "test");
p->age = 22;
printf("p->name = %s, p->age=%d\n", p->name, p->age);
printf("(*p).name = %s, (*p).age=%d\n", (*p).name, (*p).age);
free(p);
p = NULL;
return 0;
}
2. 情况要考虑全面
当两个整数是不同位数时,后面单个的整数不能直接赋值给和,仍需考虑是否有进位的情况。
和的位数可能比两个整数的位数都大。
例如:输入[9,9,9,9,9,9,9] , [9,9,9,9]
源代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int key = 0;
struct ListNode *temp;
struct ListNode *l = (struct ListNode*)malloc(sizeof(struct ListNode));
temp = l;
//不带头结点的单链表
int sum = l1->val + l2->val + key;
if (sum < 10)
{
l->val = sum;
}
else
{
l->val = sum%10;
key = sum/10;
}
l->next = NULL;
l1 = l1->next;
l2 = l2->next;
while(l1 != NULL&&l2 != NULL)
{
struct ListNode *node= (struct ListNode*)malloc(sizeof(struct ListNode));
int sum = l1->val + l2->val + key;
if (sum < 10)
{
node->val = sum;
node->next = NULL;
key = 0;
}
else
{
node->val = sum%10;
node->next = NULL;
key = sum/10;
}
while(l->next != NULL)
{
l = l->next;
}
l->next = node;
l1 = l1->next;
l2 = l2->next;
}
while(l1 != NULL)
{
struct ListNode *node= (struct ListNode*)malloc(sizeof(struct ListNode));
sum = l1->val + key;
if (sum < 10)
{
node->val = sum;
key = 0;
}
else{
node->val = sum%10;
key = sum/10;
}
node->next = NULL;
while(l->next != NULL)
{
l = l->next;
}
l->next = node;
l1 = l1->next;
}
while(l2 != NULL)
{
struct ListNode *node= (struct ListNode*)malloc(sizeof(struct ListNode));
sum = l2->val + key;
if (sum < 10)
{
node->val = sum;
key = 0;
}
else{
node->val = sum%10;
key = sum/10;
}
node->next = NULL;
while(l->next != NULL)
{
l = l->next;
}
l->next = node;
l2 = l2->next;
}
//考虑到和的位数会比两个整数的位数都大
if (key != 0)
{
struct ListNode *node= (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = key;
node->next =NULL;
while(l->next != NULL)
{
l = l->next;
}
l->next = node;
}
return temp;
}