PDA

View Full Version : [q]



abcdef
16-02-2003, 15:04
Xem hộ mình chương trình tính tổng hai đa thức, với đa thức được lưu trữ dưới dạng danh sách nối đơn có ba trường hệ số (coef), số mũ (exp) và link (next). Lỗi ở đâu mà không chạy? Thanhks.



#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct Node{
int coef;
int exp;
struct Node* next;
};
typedef struct Node node;
void nhapdt(node* first, node* end);
void attack(int h, int m, node* first, node* end);
void padd(node* a, node* b, node* c);
void indt(node* a);
void free_memory(node* a);
void main()
{
node *p,*q,*endp, *endq, *tong;
p = NULL;
q = NULL;
endp = (node*)malloc(sizeof(node));
endq = (node*)malloc(sizeof(node));
tong = NULL;
printf("Nhap da thuc P:\n");
nhapdt(p, endp);
printf("\nNhap da thuc Q:\n");
nhapdt(q, endq);
printf("\nDa thuc P:\n");
indt(p);
printf("\nDa thuc Q:\n");
indt(q);
printf("\nDa thuc tong:\n");
indt(tong);
free_memory(p);
free_memory(q);
free_memory(tong);
getch();
}
void nhapdt(node* first, node *end)
{
char ch;
int hs,sm;
char buff[80];
do
{
printf("Nhap vao he so: ");
scanf("%d", &hs);
printf("Nhap vao so mu: ");
scanf("%d", &sm);
attack(hs, sm, first, end);
gets(buff);
printf("Nhap nua hay khong(y/n)?: ");
scanf("%c", &ch);
}
while(ch == 'y');
}
void attack(int h, int m, node* first, node* end)
{
node* new_node;
new_node = (node*)malloc(sizeof(node));
new_node->coef = h;
new_node->exp = m;
new_node->next = NULL;
end->next = new_node;
end = new_node;
if(first == NULL)
first=new_node;
}
void padd(node* p,node* q,node* tong)
{
node *firstp, *firstq, *end;
int x;
firstp = p;
firstq = q;
tong = NULL;
end = (node*)malloc(sizeof(node));
while (firstp != NULL && firstq != NULL)
{
if(firstp->exp == firstq->exp)
{
x = firstp->coef + firstq->coef;
if(x != 0)
attack(x, firstp->exp, tong, end);
firstp = firstp->next;
firstq = firstq->next;
}
else if(firstp->exp >firstq->exp)
{
attack(firstp->coef, firstp->exp, tong, end);
firstp = firstp->next;
}
else
{
attack(firstq->coef, firstq->exp, tong, end);
firstq = firstq->next;
}
}
while (firstp != NULL)
{
attack(firstp->coef, firstq->exp, tong, end);
firstp = firstp->next;
}
while (firstq != NULL)
{
attack(firstq->coef, firstq->exp, tong, end);
firstq = firstq->next;
}
}
void indt(node *a)
{
node *l;
l=a;
while(l->next != NULL)
{
printf("%d*x^%d + ", l->coef, l->exp);
l=l->next;
}
printf("%d*x^%d", l->coef, l->exp);
}
void free_memory(node* a)
{
node* current, *the_next;
current = a;
while(current != NULL)
{
the_next = current->next;
free(current);
current = the_next;
}
}

abcdef
16-02-2003, 23:48
Thôi không cần nữa mình đã sửa được rồi. Thanks mọi người đã đọc.