使用链表创建多项式存储
键盘输入指定多项式的项数,然后分别输入各项的系数和指数,链表自动按照指数从小到大排列
// 使用链表创建多项式
#include <stdio.h>
#include <stdlib.h>
struct pnote //多项式各项结点结构体
{
float ceof;
int expn;
struct pnote *next;
};
struct polyn_head //多项式头结点结构体
{
struct pnote *next;
int num; //储存多项式项数
};
void creat_polyn(struct polyn_head*, int);
void output(struct polyn_head *head);
int main()
{
struct polyn_head polyn1;
struct polyn_head *head;
int n;
head = &polyn1;
printf("请输入多项式的项数:");
scanf("%d", &n);
creat_polyn(head, n);
output(head);
}
//定义使用链表创建多项式的函数
void creat_polyn(struct polyn_head *head, int n)
{
head->num = n;
struct pnote *s, *p, *q;
s = (struct pnote *)malloc(sizeof(struct pnote)); //添加第一项
printf("请分别输入该项系数和指数,用空格隔开:");
scanf("%f %d", &s->ceof, &s->expn);
s->next = NULL;
head->next = s;
s = (struct pnote *)malloc(sizeof(struct pnote)); //添加第2项
printf("请分别输入该项系数和指数,用空格隔开:");
scanf("%f %d", &s->ceof, &s->expn);
p = head->next;
if(s->expn < p->expn)
{
s->next = head->next;
head->next = s;
}
else if(s->expn > p->expn)
{
p->next = s;
s->next = NULL;
}
for(int i = 1; i < n - 1; i++)
{
s = (struct pnote *)malloc(sizeof(struct pnote)); //添加第一项
printf("请分别输入该项系数和指数,用空格隔开:");
scanf("%f %d", &s->ceof, &s->expn);
p = head->next;
q = p->next;
if(s->expn < p->expn)
{
s->next = head->next;
head->next = s;
}
else if(s->expn > p->expn)
{
//为了能够实现这一步,必须已经拥有p、q两个结点。
while(q && s->expn > q->expn)
{
p = q;
q = q->next;
}
s->next = q;
p->next = s;
}
}
}
void output(struct polyn_head *head)
{
struct pnote *p;
p = head->next;
while(p->next)
{
printf("%.2fx^%d + ", p->ceof, p->expn);
p = p->next;
}
printf("%.2fx^%d ", p->ceof, p->expn);
}