马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 a327904410 于 2022-3-14 15:43 编辑 #include<stdio.h>
#include<stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
void InitNode(struct ListNode** l) {
*l = (struct ListNode*)malloc(sizeof(struct ListNode));
if (*l == NULL) {
printf("分配空间失败!");
}
(*l)->next = NULL;
}
// 把数组里数据插进链表
int InsNode(struct ListNode* l, int *sz, int len) {
struct ListNode* p = l;
int i;
for (i = 0; i < len; i++) {
struct ListNode* s;
s = (struct ListNode*)malloc(sizeof(struct ListNode));
s->val = sz[i];
s->next = p->next;
p->next = s;
}
return 1;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int tmp = 0;
struct ListNode* p1 = l1->next, * p2 = l2->next;
struct ListNode* sum;
InitNode(&sum);
while (p1 != NULL || p2 != NULL) {
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
int num1, num2, he;
if (p1 != NULL) {
num1 = p1->val;
p1 = p1->next;
}
if (p2 != NULL) {
num2 = p2->val;
p2 = p2->next;
}
he = num1 + num2 + tmp;
tmp = he / 10;
he = he % 10;
s->val = he;
s->next = sum->next;
sum->next = s;
}
if (tmp != 0) {
struct ListNode* s = (struct ListNode*)malloc(sizeof(struct ListNode));
s->val = tmp;
s->next = sum->next;
sum->next = s;
}
return sum;
}
void DispNode(struct ListNode* l) {
struct ListNode* p = l->next;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
}
int main() {
struct ListNode* l1, * l2;
InitNode(&l1);
InitNode(&l2);
int sz1[] = { 1,2,3 };
int sz2[] = { 4,5,6 };
int len1 = sizeof(sz1) / sizeof(int);
int len2 = sizeof(sz2) / sizeof(int);
InsNode(l1, sz1, len1);
InsNode(l2, sz2, len2);
struct ListNode* sum = addTwoNumber(l1, l2); // 在这里调用这个函数,我这个方法好像是错的
DispNode(sum);
return 0;
}
不知道是不是你要的: #include <stdio.h>
#include <malloc.h>
typedef struct ListNode{
int val;
struct ListNode *next;
}ListNode;
ListNode *sum(ListNode *a, ListNode *b){
if(a && b) {
ListNode *res = (ListNode*)malloc(sizeof(ListNode));
res->val = a->val + b->val;
res->next = NULL;
return res;
}
return NULL;
}
ListNode *FREE_ALL(ListNode *head){
if(head){
while(head){
ListNode *p = head;
head = head->next;
free(p);
}
return head;
}
return NULL;
}
int main(){
ListNode *A, *B, *C;
A = (ListNode*)malloc(sizeof(ListNode));
B = (ListNode*)malloc(sizeof(ListNode));
A->val = 13;
A->next = NULL;
B->val = 4;
A->next = NULL;
C = sum(A, B);
printf("C->val: %d", C->val);
// ----- 释放内存 -----
A = FREE_ALL(A);
B = FREE_ALL(B);
C = FREE_ALL(C);
free(A);
free(B);
free(C);
return 0;
}
|