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

nhập vào một ngăn xếp, in ra ngăn xếp sau khi sắp xếp thứ tự và loại bỏ phần tử trùng


#include<conio.h>
#include<stdio.h>
#define Maxlength 100
typedef int ElementType;
typedef int Position;
typedef struct
{
    ElementType Elements[Maxlength];
    int Top_idx;
}Stack;
// tao ngan xep rong
void MakeNull_Stack(Stack &S)
{
    S.Top_idx=Maxlength;
}
// kiem tra ngan xep rong
int Empty_Stack(Stack S)
{
    return S.Top_idx==Maxlength;
}
// kiem tra ngan xep day
int Full_Stack(Stack S)
{
    return S.Top_idx==0;
}
// lay noi dung phan tu tai vi tri dinh cua gan xep
ElementType Top(Stack S)
{
    if (!Empty_Stack(S))
        return S.Elements[S.Top_idx];
    else
        printf("Loi! Ngan xep rong");
}
//xoa phan tu ra khoi ngan xep
void Pop(Stack &S)
{
    if(!Empty_Stack(S))
        S.Top_idx=S.Top_idx+1;
    else
        printf("Loi! Ngan xep rong");
}
//them phan tu vao ngan xep
void Push(ElementType X, Stack &S)
{
    if(Full_Stack(S))
        printf("Loi! ngan xep day");
    else
    {
        S.Top_idx=S.Top_idx-1;
        S.Elements[S.Top_idx]=X;
    }
}
// sap xep thep kieu diet toan bo
void Sort(Stack &S)
{
    ElementType Temp;
    for(int i=S.Top_idx;i<Maxlength;i++)
        for(int j=i+1;j<=Maxlength;j++)
            if(S.Elements[i]>S.Elements[j])
                {
                    Temp=S.Elements[i];
                    S.Elements[i]=S.Elements[j];
                    S.Elements[j]=Temp;
                }
}
//xoa phan tu tai vi tri X trong ngan xep
void Delete(Position X, Stack &S)
{
    X=S.Top_idx+X;
    ElementType Temp;

    while(!(X==S.Top_idx))
    {
        Temp=S.Elements[X];
        S.Elements[X]=S.Elements[X-1];
        S.Elements[X-1]=Temp;
        X--;
    }
    Pop(S);
}

void Distinc(Stack &S)
{
 for(int i=S.Top_idx;i<Maxlength-1;i++)
  for(int j=i+1; j<Maxlength;j++)
  {
   if (S.Elements[i]==S.Elements[j])
   {
   Delete(j-S.Top_idx,S);
   i++;
  // j++;
   }

}
}

void Inp_Stack(Stack &S)
{
    int n;
    ElementType x;
    printf("\t- Nhap vao so phan tu ngan xep: ");
    scanf("%d",&n);
    for( int i=0;i<n;i++)
    {
        printf("\t - Nhap phan tu thu %d: ",i);
        scanf("%d",&x);
        Push(x,S);
    }
}
void Out_Stack(Stack S)
{
    while(!Empty_Stack(S))
    {
        printf("%4d",S.Elements[S.Top_idx]);
        Pop(S);
    }
}
main()
{
    Stack S;
    MakeNull_Stack(S);
    Inp_Stack(S);

    printf("\n\t=> Ngan xep cua ban vua nhap: \n");
    Out_Stack(S);

    Sort(S);
    printf("\n\t=> Ngan xep da sap xep: \n");
    Out_Stack(S);

   Distinc(S);

    printf("\n\t=> Ngan xep da loai bo phan tu trung: \n");
    Out_Stack(S);

    getch();
}

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