C 循环链表中的多项式
打印多项式时,第一个系数和指数将重复打印n次(项数) 代码如下:C 循环链表中的多项式,c,C,打印多项式时,第一个系数和指数将重复打印n次(项数) 代码如下: #include<stdio.h> #include<stdlib.h> struct Node{ int coef , exp; struct Node* next; }; struct Node* create( struct Node* ); int main(){ int val , choice , loc; struct Node* A = NULL;
#include<stdio.h>
#include<stdlib.h>
struct Node{
int coef , exp;
struct Node* next;
};
struct Node* create( struct Node* );
int main(){
int val , choice , loc;
struct Node* A = NULL;
struct Node* B = NULL;
A = create( A );
B = create( B );
display( A );
display( B );
do{
printf("\n\n-----POLYNOMIAL OPERATIONS-----\n1.Addition\n2.Multiply\n3.Evaluate\n4.Exit\n--->");
scanf("%d",&choice);
switch( choice ){
case 1://Adding
break;
case 2://Multiplying
break;
case 3://Evaluating
break;
}
}while( choice != 4 );
return 0;
}
struct Node* create( struct Node* p ){
int i , c , x , t;
printf("\nNumber of terms: ");
scanf("%d",&t);
for( i = 0 ; i < t ; i++ ){
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
printf("Enter Coefficient & Exponent: ");
scanf("%d%d",&c,&x);
temp->coef = c;
temp->exp = x;
if( p == NULL ){
p = temp;
temp->next = p;
}else{
struct Node* temp1 = p;
while( temp1->next != p ) temp1 = temp1->next;
temp1->next = temp;
temp->next = p;
}
}
return p;
}
void display( struct Node* p ){
struct Node* temp = p;
printf("\nPOLYNOMIAL: ");
do{
printf("%dx^(%d)",p->coef,p->exp);
temp = temp->next;
if( temp != p ){
printf(" + ");
}
}while( temp != p );
}
#包括
#包括
结构节点{
int coef,exp;
结构节点*下一步;
};
结构节点*创建(结构节点*);
int main(){
int val,choice,loc;
结构节点*A=NULL;
结构节点*B=NULL;
A=创建(A);
B=创建(B);
显示器(A);
显示器(B);
做{
printf(“\n\n-----多项式运算------\n1.加法\n2.乘法\n3.求值\n4.退出\n-->”);
scanf(“%d”,选择(&C);
开关(选择){
案例1://添加
打破
案例2://乘法
打破
案例3://评估
打破
}
}while(选项!=4);
返回0;
}
结构节点*创建(结构节点*p){
int i,c,x,t;
printf(“\n条款编号:”);
scanf(“%d”、&t);
对于(i=0;i系数=c;
温度->经验=x;
if(p==NULL){
p=温度;
温度->下一步=p;
}否则{
结构节点*temp1=p;
而(temp1->next!=p)temp1=temp1->next;
temp1->next=temp;
温度->下一步=p;
}
}
返回p;
}
无效显示(结构节点*p){
结构节点*temp=p;
printf(“\n语法:”);
做{
printf(“%dx^(%d)”,p->coef,p->exp);
温度=温度->下一步;
如果(温度!=p){
printf(“+”);
}
}while(temp!=p);
}
您只需更改:
do{
printf("%dx^(%d)",temp->coef,temp->exp);
temp = temp->next;
...
现在,每次通过显示循环时,都将取消对初始节点的引用
我想指出的是,由于现在编写了
display()
函数,如果向其传递了空指针,则会出现segfault。如果在函数create
中的Number of terms:
的任一提示下输入0
,您将temp
的.next
字段链接到temp
(因为您这样做了p=temp;temp->next=p;
)。为什么要使用循环列表?为什么不定期(非循环)列表?我看不出有什么明显的好处。
do{
printf("%dx^(%d)",temp->coef,temp->exp);
temp = temp->next;
...