能详细解释一下初始化吗
为什么要判断新节点是不是空的?不是已经开辟空间了吗
为什么不能输出呢应该怎么改
#include <stdio.h>
#include <stdlib.h>
//一元多项式相加
typedef struct Node{
int floatcoef; //序数
int intexpn; //指数
struct Node* next;
}Node;
Node* creat(){
Node* head=(Node*)malloc(sizeof(Node));
Node* tail=head;
int coef;//序数
int expn;//指数
scanf("%d %d",&coef,&expn);
while(coef!=0){//////////////////
Node* node=(Node*)malloc(sizeof(Node));
if(node!=NULL){///////////
node->floatcoef=coef;
node->intexpn=expn;
}
node->next=NULL;
tail->next=node;
tail=node;
scanf("%d %d",&coef,&expn);
}
return head;
}
Node* addpoly(Node* leftpoint,Node* rightpoint){
Node* head1=leftpoint->next;
Node* head2=rightpoint->next;
Node* temp=leftpoint;
while(head1!=NULL&&head2!=NULL){
if(head1->intexpn<head2->intexpn){
temp->next=head1;
head1=head1->next;
temp=temp->next;
}
else if(head2->intexpn<head1->intexpn){
temp->next=head2->next;
head2=head2->next;
temp=temp->next;
}
else{
head1->intexpn+=head2->intexpn;
temp->next=head1;
temp=temp->next;
head1=head1->next;
head2=head2->next;
}
}
if(head1!=NULL){
temp->next=head1;
}
else if(head2!=NULL){
temp->next=head2;
}
return leftpoint;
}
void print(Node* h){
Node* cur=h->next;
printf("%dx^%d",&cur->floatcoef,&cur->intexpn);
cur=cur->next;
while(cur){
if(cur->floatcoef==0);
else{printf("+%dx^%d",cur->floatcoef,cur->intexpn);}
cur=cur->next;
}
}
int main()
{
Node* a=creat();
print(a);
Node* b=creat();
print(b);
// Node* c=addpoly(a,b);
//print(c);
return 0;
}
因为在用malloc()函数申请结点空间时,有可能会出现不成功的现象,此时malloc() 返回的是个空指针 NULL , 所以为了代码可靠健壮后面加一判断 if(node!=NULL) 确保正确运行。
【相关推荐】
int cal(int n) {
int ret = 0;
int i = 1;
for (; i < n; ++i) { //第一段 这个函数的复杂度是O(n)
ret = ret + f(i);
}
}
int f(int n) {
int sum = 0;
int i = 1;
for (; i < n; ++i) {//第段段 这函数的复杂度是O(n),合起来就是O(n^2)
sum = sum + i;
}
return sum;
}
这里单看第一段函数的复杂度是O(n),单看第二段函数的复杂度也是O(n),有因为嵌套了,合在一起就是O(n^2)了。