Thứ Bảy, 13 tháng 12, 2014

nhập vào một danh sách, in ra danh sách sau khi đã loại bỏ phần tử trùng và xếp theo thứ tự tăng dần của danh sách




#include<stdio.h>
#include<conio.h>
#define Maxlength 1000
typedef int ElementType;
typedef int Position;
typedef struct
{
    ElementType Elements[Maxlength];
    Position Last;
}List;

void MakeNull_List(List &L)
{
    L.Last=0;
}

int Empty_List(List &L)
{
    return L.Last==0;
}
Position First_List(List &L)
{
    return 1;
}
Position End_List(List &L)
{
    return L.Last+1;
}
Position Next(Position P, List &L)
{
    return P++;
}
Position Retrieve(Position P, List &L)
{
    return L.Elements[P-1];
}
void Insert_List(ElementType X, Position P, List &L)  /
{
    if(L.Last==Maxlength)
            printf("\tDanh sach day!");
    else
        if ((P<1)||(P>L.Last+1))
                printf("\tVi tri khong hop le!");
        else
        {
            for(Position Q=L.Last;Q>P-1;Q--)
                L.Elements[Q]=L.Elements[Q-1];
            L.Elements[P-1]=X;
            L.Last++;
        }

}
void Delete_List(Position P, List &L)
{
    if ((P<0)||(P>L.Last))
            printf("\t Vi tri khong hop le");
    else
    {
        Position Q;
        for(Q=P;Q<L.Last;Q++)
            L.Elements[Q-1]=L.Elements[Q];
        L.Last--;
    }
}
void Read_List(List &L)  //Nhâ?p danh sa´ch va`o
{
    MakeNull_List(L);
    int X,N;
    printf("\t-Nhap so phan tu cua sanh sach: "); scanf("%d",&N);

    for(int i=1;i<=N;i++)
    {
        printf("\t\t- Nhap phan tu thu %d: ",i);
        scanf("%d",&X);
        Insert_List(X,i,L);
    }
}
void Print_List(List &L)
{
    if (Empty_List(L)) printf("\t=> Danh sach rong!");
    else
        for(int i=1;i<=L.Last;i++)
            printf("%4d",Retrieve(i,L));
}
void Sort_List(List &L)
{
    for(int i=First_List(L)-1;i<End_List(L)-1;i++)
        for (int j=i+1;j<End_List(L)-1;j++)
            if(L.Elements[i]>L.Elements[j])
                    {
                        int Temp=L.Elements[i];
                        L.Elements[i]=L.Elements[j];
                        L.Elements[j]=Temp;
                    }
}

void Distinc(List &L)
{
    for (int i=First_List(L)-1;i<End_List(L)-1;i++)
        for(int j=i+1;j<End_List(L)-1;j++)
            if(L.Elements[i]==L.Elements[j])
                Delete_List(j,L);
}

main()
{
    List L;
    Position P;
    Read_List(L);

    printf("\n\t==> Danh sach cua ban: \n");
    Print_List(L);

    Sort_List(L);
    printf("\n\t==> Danh sach cua ban da sap xep: \n");
    Print_List(L);

    Distinc(L);
    printf("\n\t==> Danh sach sao khi loc: \n");
    Print_List(L);

    getch();
    return 0;
}

Không có nhận xét nào: