gpt4 book ai didi

c - 如何有效地添加 2 个不同大小的链表

转载 作者:太空宇宙 更新时间:2023-11-04 04:45:14 24 4
gpt4 key购买 nike

我在将两个不同大小的链表相加时遇到问题。他们已经逆转了。其他一切似乎都有效,但我知道问题出在 while 循环中

 while(num1 != NULL && num2 != NULL)

当我使用 && 运算符时,它只会停止到第一个完成列表的末尾(我明白这一点)。但是,当我尝试使用 or (||) 运算符时,我的整个程序都崩溃了。请有人帮我找出问题所在。

这是函数。和我的主要。

//adds the two linked lists for their sum
node *addLargeNumber(node *num1, node *num2) {
node *result = NULL;
node *prev = NULL;
node *temp;
int sum, carry = 0;

while(num1 != NULL || num2 != NULL) { //while both lists exists or either is not empty
/*calculate values for the result. the next digit with be the sum of the carry
from previous number(if any) digit from 1st list and digit from second list*/

sum = carry + (num1->data) + (num2->data);
if (sum > 9) carry = 1;
else carry = 0;
sum = sum % 10; //just want ones column from sum to put in result
temp = createNode(sum);

if(result == NULL)
result = temp; //if it is first node, make it the head
else
prev->next = temp; //if not first node, connect it to rest
prev = temp; //reset prev or next insertion

// move to next nodes in both lists
if(num1 != NULL) num1 = num1->next;
if(num2 != NULL) num2 = num2->next;
}

if(carry > 0) temp->next = createNode(carry);
return result;
}

主要功能

int main(void) {
node *storeNumber();
void reverseList();
void printList();
node *addLargeNumber();
node *add();

char number1[numsize], number2[numsize], bigSum[numsize];
node *top;
char command;
int number;

FILE *in = fopen("input.txt", "r");
FILE *out = fopen("output.txt", "w");

while(fscanf(in, "%c", &command) != EOF) { //while there are no more commands to be read
top = NULL;
//adding two large numbers with linked list
if(command == 'A') {
fscanf(in, "%s", &number1);
fscanf(in, "%s", &number2);
node *top1 = storeNumber(number1);
node *top2 = storeNumber(number2);
node *sum = addLargeNumber(top1, top2);

printList(top1);
printf(" + ");
printList(top2);
printf(" = ");
printList(sum);
printf("\n\n");
fscanf(in, "%c", &command);
}
}
system("Pause");
return 0;
}

最佳答案

如果你使用 || “或”运算符,num 之一可能为 null,当您尝试访问 num1->data 时程序崩溃或 num2->data

尝试类似的东西:

 sum = carry;
if(num1 != NULL) sum += num1->data;
if(num2 != NULL) sum += num2->data;

 if(num1!= NULL) num1 = num1->next;
if(num2!= NULL) num2 = num2->next;

关于c - 如何有效地添加 2 个不同大小的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21800428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com