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

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


#include<conio.h>
#include<stdio.h>
#define Maxlength 100

typedef int ElementType;
typedef int Position;
typedef struct
{
 ElementType Elements[Maxlength];
 Position Front, Rear;
}Queue;

void MakeNull_Queue(Queue &Q)
{
 Q.Front = -1;
 Q.Rear = -1;
}

int Empty_Queue(Queue Q)
{
 return Q.Front == -1;
}

int Full_Queue(Queue Q)
{
 return (Q.Rear - Q.Front + 1) == Maxlength;
}
void DeQueue(Queue &Q)
{
 if (!Empty_Queue(Q))
 {
  Q.Front = Q.Front + 1;
  if (Q.Front > Q.Rear) MakeNull_Queue(Q);
 }
 else
  printf("Loi: Hang rong!");
}
void EnQueue(ElementType X, Queue &Q)
{

  if (!Full_Queue(Q))
 {
  if (Empty_Queue(Q)) Q.Front = 0;
  if (Q.Rear == Maxlength - 1)
  {
   for (int i = Q.Front; i <= Q.Rear; i++)
    Q.Elements[i - Q.Front] = Q.Elements[i];
   Q.Rear = Maxlength - Q.Front - 1;
   Q.Front = 0;
  }
  Q.Rear = Q.Rear + 1;
  Q.Elements[Q.Rear] = X;
 }
 else printf("Loi: Hang doi day!");
}
void Inp_Queue(Queue &Q)
{
 Position n;
 printf("\t- So phan tu hang doi: ");
 scanf("%d",&n);

  Q.Front = 0;
 Q.Rear = n - 1;
 Position i;
 for (i = Q.Front; i <= Q.Rear; i++)
 {
  printf("\t - Nhap phan tu thu %d : ",i);
  scanf("%d",&Q.Elements[i]);
 }

}
void Out_Queue(Queue Q)
{
 for (int i = Q.Front; i <= Q.Rear; i++)
  printf("%5d",Q.Elements[i]);
 printf("\n");
}
void Sort_Queue(Queue &Q)
{

  for (int i = Q.Front; i < Q.Rear; i++)
 for (int j = i + 1; j <= Q.Rear; j++)
 {
  if (Q.Elements[i]>Q.Elements[j])
  {
   Q.Elements[i] = Q.Elements[i] + Q.Elements[j];
   Q.Elements[j] = Q.Elements[i] - Q.Elements[j];
   Q.Elements[i] = Q.Elements[i] - Q.Elements[j];
  }
 }
}
void DelX_Queue(Position X, Queue &Q)
{
 if (!((X >= Q.Front) && (X <= Q.Rear)))
  printf("\tVi tri Can xoa khong ton tai!");
 else
 {
  for (int i = X; i > Q.Front; i--)
   Q.Elements[i] = Q.Elements[i - 1];
 }
 DeQueue(Q);

}
void Distinc_Queue(Queue &Q)
{
 for (int i = Q.Front; i <Q.Rear;i++)
 for (int j = i + 1; j <= Q.Rear;j++)
 if (Q.Elements[i] == Q.Elements[j])
 {
  DelX_Queue(j, Q);
  i++;
 }

}
main()
{
int n;
 Queue Q;
 Position t=2;


  Inp_Queue(Q);

  printf("\t =>Hang doi ban da nhap: \n");
 Out_Queue(Q);
 printf("\n");

  Sort_Queue(Q);
 printf("\t =>Hang doi ban da sap xep: \n");
 Out_Queue(Q);
 printf("\n");

  Distinc_Queue(Q);
 printf("\t =>Hang doi ban da loai bo phan tu trung: \n");
 Out_Queue(Q);
 printf("\n");


  DeQueue(Q);
 printf("\t =>Hang doi ban da xoa phan tu dau: \n");
 Out_Queue(Q);
 printf("\n");

printf("\n them phan tu n vao hang doi: "); scanf("%d",&n);
 ElementType X=n;

  EnQueue(X, Q);
 printf("\t =>Hang doi them X=%d vao cuoi: \n",X);
 Out_Queue(Q);
 printf("\n");

  getch();
}

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