Code:
#include "conio.h"
#include "stdio.h"
#include "alloc.h"
#include "math.h"
typedef struct PhanSo {
int Tu;
int Mau;
};
typedef PhanSo ElementType;
typedef struct Node {
ElementType Element;
Node *Next;
};
typedef Node *Stack;
//khoi tao danh sach rong
Stack MakeNull_Stack(){
Stack Header = (Node*)malloc(sizeof(Node));
(Header)->Next = NULL;
return Header;
}
//kiem tra danh sach rong
char Empty_Stack(Stack S) {
return S->Next == NULL;
}
//Khoi tao 1 node
Node *Make_Node(ElementType X) {
Node *temp = (Node*)malloc(sizeof(Node));
temp->Element = X;
return temp;
}
//xem mot phan tu vao stack
void Push(ElementType X, Stack P) {
Node *Temp = Make_Node(X);
Temp->Next = P->Next;
P->Next = Temp;
}
//day 1 phan tu ra khoi stack
void Pop(Stack P){
Stack Temp;
if (!Empty_Stack(P)){
Temp = P->Next;
P->Next = Temp->Next;
free(Temp);
}
}
//nhap phan so
PhanSo Nhap(){
PhanSo temp;
printf("\tTu: ");
scanf("%d",&temp.Tu);
temp.Mau = 0;
while(temp.Mau == 0)
{
printf("\tMau: ");
scanf("%d",&temp.Mau);
}
return temp;
}
//nhap n phan so
Stack Input_Stack(int n) {
Stack L = MakeNull_Stack();
ElementType x;
for(int i = 1; i<=n; i++) {
printf("Phan tu %d \n",i);
x = Nhap();
Push(x,L);
}
return L;
}
//tim uoc chung lon nhat cua hai so a va b
int UCLN(unsigned int a, unsigned int b) {
if(a==b)
return a;
else
if(a>b)
return UCLN(a-b,b);
else
return UCLN(a,b-a);
}
// Rut gon phan so
PhanSo RutGon(PhanSo p) {
PhanSo temp = p;
int k = UCLN(abs(temp.Tu),abs(temp.Mau));
temp.Tu/=k;
temp.Mau/=k;
return temp;
}
//tong hai phan so
PhanSo Tong(PhanSo p, PhanSo q) {
PhanSo temp = {p.Tu*q.Mau + q.Tu*p.Mau,p.Mau*q.Mau};
temp = RutGon(temp);
return temp;
}
//tong cac phan so trong stack
PhanSo Tong(Stack S) {
PhanSo temp = {0,1};
while(!Empty_Stack(S)){
temp = Tong(temp,S->Next->Element);
Pop(S);
}
return temp;
}
//xuat phan so
void Xuat(PhanSo p) {
printf("%d/%d\t",p.Tu,p.Mau);
}
//xat ngan xep
void Out_Stack(Stack L) {
while(!Empty_Stack(L)) {
Xuat(L->Next->Element);
Pop(L);
}
}
void main() {
clrscr();
int n;
printf("Nhap vao n = ");
scanf("%d",&n);
Stack L = Input_Stack(n);
printf("\nTong cac phan so: ");
Xuat(Tong(L));
getch();
}