數據結構實驗-線性表及其的基本操作

數據結構實驗-線性表及其的基本操作
實驗內容:
1.定義一個一元多項式結構,完成一元多項式的建立,加法和減法以及輸出算法的實現。
2.選作:完成一元多項式的乘法操作。
代碼:
#include<stdio.h>
#include<stdlib.h>
typedef struct NODE
{
int coef; ///係數
int exp; ///指數
struct NODE *next;
}polynode,*Polylist;

int output_list(Polylist head);
Polylist Creat_list()
{ ///創建鏈表
Polylist head,rear,s;
head = (Polylist)malloc(sizeof(polynode));
rear = head;
while(1)
{
printf(“input the coef,exp:\n”);
s = (Polylist)malloc(sizeof(polynode));
scanf("%d", &s->coef);
if(!s->coef)
{
free(s);
break;
}
scanf("%d", &s->exp);
rear->next = s;
rear = s;
}
rear->next = NULL;
return (head);
}
Polylist add_list(Polylist head1,Polylist head2)
{ ///多項式加法
Polylist p, q, s, head, tail;
p = head1->next;
q = head2->next;
tail = head = (Polylist)malloc(sizeof(polynode));
while(p && q)
{
s = (Polylist)malloc(sizeof(polynode));
if(p->exp < q->exp)
{ ///當P的指數小於Q的指數時
s->coef = p->coef;
s->exp = p->exp;
tail->next = s;
tail = s;
tail ->next = NULL;
p = p->next;
}
else if(p->exp == q->exp)
{ ///當指數相等時
s->coef = p->coef + q->coef;
s->exp = p->exp;
if (!s->coef)
{
free(s);
}
else
{
tail->next = s;
tail = s;
tail ->next = NULL;
}
p = p->next;
q = q->next;
}
else
{
s->coef = q->coef;
s->exp = q->exp;
tail->next = s;
tail = s;
tail ->next = NULL;
q = q->next;
}
}
if§
tail->next = p;
else
tail->next = q;
return head;
}

Polylist sub_list(Polylist head1,Polylist head2)
{ ///多項式減法
Polylist p ,head;
p = head2->next;
do
{
p->coef = -p->coef;
p = p->next;
}while§;
head =add_list(head1,head2);
return head;
}

Polylist polyadd_list(Polylist head)
{ ///合併多項式
Polylist p,q,m;
p = m = head->next;
while(p ->next )
{
m = p;
q = p->next;
while(q)
{
if(q->exp == p->exp)
{
p->coef += q->coef;
m->next = q->next;
free(q);
q = m->next;
}
else
{
m = q;
q = q->next;
}
}
p = p->next;
}
return head;
}

Polylist multi_list(Polylist head1,Polylist head2)
{ ///多項式乘法
Polylist head,p,q,r,m;
head = r = (Polylist)malloc(sizeof(polynode));
for(p = head1->next;p != NULL;p = p->next)
{
for(q = head2->next;q != NULL;q = q->next)
{
m = (Polylist)malloc(sizeof(polynode));
m->coef = p->coef * q->coef;
m->exp = p->exp + q->exp;
r->next = m;
r = m;
}
}
r->next = NULL;
output_list(head);
polyadd_list(head);
return head;
}

int output_list(Polylist head)
{ ///輸出多項式
Polylist p;
int n = 1;
for(p = head->next;p !=NULL;p = p->next)
{
printf(“第%d項:%d %d \n”, n++,p->coef,p->exp);
}
return 0;
}

int main()
{
Polylist head1,head2,head;
head1 = Creat_list();
head2 = Creat_list();

printf(“多項式加法:\n”);
head =add_list(head1,head2);
output_list(head);
printf(“多項式減法:\n”);
head = sub_list(head1,head2);
output_list(head);

printf(“多項式乘法:\n”);
head = multi_list(head1,head2);
output_list(head);
return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章