【发布时间】:2020-11-05 17:01:08
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
struct node{
int coff;
int pow;
struct node* next;
};
struct node* head1 = NULL;
struct node* head2 = NULL;
void insert(int c, int p, struct node* head){
struct node* newnode = (struct node*)malloc(sizeof(struct node));
struct node* temp = head;
newnode->coff = c;
newnode->pow = p;
newnode->next = NULL;
if(head == NULL){
head = newnode;
}else{
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newnode;
}
}
void display(struct node* h){
struct node* temp;
temp = h;
while(temp != NULL){
printf("%dx^%d ", temp->coff, temp->pow);
temp = temp->next;
}
printf("\n");
}
int main(){
insert(3,2,head1);
insert(5,1,head1);
insert(4,0,head1);
insert(9,2,head2);
insert(6,1,head2);
insert(2,0,head2);
display(head1);
display(head2);
return 0;
}
我已经为我的链表创建了节点结构。然后我为插入和显示多项式创建了两个函数。我为两个不同多项式的存储地址创建了 head1 和 head2。我想在插入和显示函数中使用 head1 和 head2 作为参数。然后最后我想打印两个多项式。但是有一个瓶颈。当我执行我的程序时,它会退出而不给出任何输出。
我的预期输出是:
3x^2 5x^1 2x^0
9x^2 6x^1 4x^0
我该如何解决这个问题?函数中的 (struct node* head) 参数有什么问题吗?为什么这个程序没有输出就退出了?
非常感谢!
【问题讨论】:
-
我认为你的意思是 9x^2 5x^1 4x^0 用于第二个输出
-
@AbhayAravinda 是的。这是我的错误。对于那个很抱歉。我将对其进行编辑。
-
关于:
struct node* newnode = (struct node*)malloc(sizeof(struct node));1) 在 C 中,返回的类型是void*,可以分配给任何指针。强制转换只会使代码混乱,使其更难以理解、调试等。 2) 始终检查 (!=NULL) 返回值以确保操作成功。如果不成功(==NULL),则调用perror( "malloc failed" );,这样系统认为发生错误的错误消息和文本原因都会输出到stderr。
标签: c function linked-list arguments polynomials