怎么修改这个链表的插入 使输出可以从小到大输出
错误的
#include
#include
typedef struct PNODE
{
float coef;
int expn;
struct PNODE*next;
}PNODE;
PNODE *insert(PNODE *head,PNODE *s);
PNODE *creatPoly(PNODE *head);
void shuchu(PNODE *head);
PNODE *addPoly(PNODE *headA,PNODE *headB);
int main()
{
PNODE *headA,*headB;
headA=creatPoly(headA);
shuchu(headA);
headB=creatPoly(headB);
shuchu(headB);
}
PNODE *creatPoly(PNODE *head)
{
int n,i;
head=NULL;
PNODE *s;
printf("输入该多项式的项数:");
scanf("%d",&n);
printf("\n输入多项式各项系数以及指数:");
for(i=1;i<=n;i++)
{
s=(PNODE*)malloc(sizeof(PNODE));
scanf("%f %d",&s->coef,&s->expn);
if(i!=1)
{
head=insert(head,s);
}
else
{
head=s;
head->next=NULL;
}
}
printf("输入完成\n");
return head;
}
PNODE *insert(PNODE *head,PNODE *s)
{
PNODE *p,*pr;
p=pr=head;
while(p->expnexpn&&p->next!=NULL)
{
pr=p;
p=p->next;
}
if(p->expn>=s->expn&&p->next!=NULL)
{
if(p==head)
{
head=s;
s->next=p;
}
else
{
pr->next=s;
s->next=p;
}
}
else
{
p->next=s;
s->next=NULL;
}
return head;
}
void shuchu(PNODE *head)
{
PNODE *p;
p=head;
printf("\n输出多项式:\n");
while(p!=NULL)
{
printf("\t%f %d,",p->coef,p->expn);
p=p->next;
}
}
修改如下,改动处见注释,供参考:
#include<stdio.h>
#include<stdlib.h>
typedef struct PNODE
{
float coef;
int expn;
struct PNODE*next;
}PNODE;
PNODE *insert(PNODE *head,PNODE *s);
PNODE *creatPoly(PNODE *head);
void shuchu(PNODE *head);
PNODE *addPoly(PNODE *headA,PNODE *headB);
int main()
{
PNODE *headA,*headB;
headA=creatPoly(headA);
shuchu(headA);
headB=creatPoly(headB);
shuchu(headB);
return 0;
}
PNODE *creatPoly(PNODE *head)
{
int n,i;
head=NULL;
PNODE *s;
printf("输入该多项式的项数:");
scanf("%d",&n);
printf("\n输入多项式各项系数以及指数:");
for(i=1;i<=n;i++)
{
s=(PNODE*)malloc(sizeof(PNODE));
s->next = NULL; //修改
scanf("%f %d",&s->coef,&s->expn);
if(i!=1)
{
head=insert(head,s);
}
else
{
head=s;
head->next=NULL;
}
}
printf("输入完成\n");
return head;
}
PNODE *insert(PNODE *head,PNODE *s)
{
PNODE *p,*pr;
p=pr=head;
while(p->next && p->next->expn < s->expn)
//(p->expn<s->expn&&p->next!=NULL) //修改
{
//pr=p; //修改
p=p->next;
}
if (p == head && p->expn > s->expn){//修改
s->next = head;
head = s;
}
else{ //修改
s->next = p->next;
p->next = s;
}
//if(p->expn>=s->expn&&p->next!=NULL)//修改 以下删除
//{
// if(p==head)
// {
// head=s;
// s->next=p;
// }
// else
// {
// pr->next=s;
// s->next=p;
// }
//}
//else
//{
// p->next=s;
// s->next=NULL;
//}
return head;
}
void shuchu(PNODE *head)
{
PNODE *p;
p=head;
printf("\n输出多项式:\n");
while(p!=NULL)
{
printf("\t%f %d,",p->coef,p->expn);
p=p->next;
}
printf("\n"); //修改
}
不知道你这个问题是否已经解决, 如果还没有解决的话: