#include <stdio.h>
#include <conio.h>
#define MaxLength 300
typedef int ElementType;
typedef int Position;
typedef struct
{
ElementType Elements[MaxLength];
Position Last;
}List;
void MakeNull_List(List *L)
{
L->Last=0;
}
Position FirstList(List L)
{
return 1;
}
Position EndList(List L)
{
return L.Last+1;
}
Position Next(Position P, List L)
{
return P+1;
}
ElementType Retrieve(Position P, List L)
{
return L.Elements[P-1];
}
void Print_List(List L)
{
Position P;
P=FirstList(L);
printf("\n bat dau in danh sach");
while(P!=EndList(L))
{
printf("\n %d",Retrieve(P,L));
P=Next(P,L);
}
printf("\n ket thuc in danh sach");
}
void Insert_List(ElementType X,Position P, List *L)
{
int i=0;
if(L->Last==MaxLength)
printf("\n danh sach day");
else
if((P<1)||(P>L->Last+1))
printf("\n vi tri khong hop le");
else
{
for(i=L->Last;i>=P;i--)
L->Elements[i]=L->Elements[i-1];
L->Last++;
L->Elements[P-1]=X;
}
}
void Read_List(List *L)
{
int i,N;
ElementType X;
MakeNull_List(L);
printf("\n nhap vao so phan tu trong danh sach: ");
scanf("%d",&N);
for(i=1;i<=N;i++)
{
printf("\n phan tu thu %d la: ",i);
scanf("%d",&X);
Insert_List(X,EndList(*L),L);
}
}
void swap(Position a, Position b, List *L)
{
ElementType temp;
temp=L->Elements[a-1];
L->Elements[a-1]=L->Elements[b-1];
L->Elements[b-1]=temp;
}
void Sort_List(List *L)
{
Position P=FirstList(*L);
while(P!=EndList(*L))
{
Position Q=Next(P,*L);
while(Q!=EndList(*L))
{
if((Retrieve(P,*L))>(Retrieve(Q,*L)))
swap(P,Q,L);
Q=Next(Q,*L);
}
P=Next(P,*L);
}
}
//them phan tu vao danh sach co thu tu
Position OrderLocate(ElementType X, List L)
{
Position P;
int found=0;
P=FirstList(L);
while((P!=EndList(L)) && (Retrieve(P,L)<X) && (found==0))
{
if(Retrieve(P,L)==X)
{
found=1;
break;
}
else P=Next(P,L);
}
return P;
}
void Insert_OrderList(ElementType X, List *L)
{
Position P=OrderLocate(X,*L);
Insert_List(X,P,L);
}
int main()
{
List L;
ElementType X;
Position P;
MakeNull_List(&L);
Read_List(&L);
printf("\n danh sach vua nhap la: \n");
Print_List(L);
Sort_List(&L);
printf("\n danh sach sau khi sap xep la: \n");
Print_List(L);
printf("\n nhap vao noi dung phan tu can them: "); scanf("%d",&X);
Insert_OrderList(X,&L);
//them phan tu vao dung vi tri trong danh sach
printf("\n danh sach sau khi them phan tu %d la: \n",X);
Print_List(L);
getch();
return 0;
}
Không có nhận xét nào:
Đăng nhận xét