Cài đặt Queue số nguyên bằng mảng một chiều trong C++
| Cài đặt Queue số
nguyên bằng mảng một chiều trong C++
Khai báo Queue
struct QUEUE
{
int front,
rear;
int Data[MAX];
int count;
};
Prototype
void Init(QUEUE&);
int
IsEmpty(QUEUE);
int IsFull(QUEUE);
void
EnQueue(QUEUE&, int);
void
DeQueue(QUEUE&, int&);
int Qfront(QUEUE);
int Qrear(QUEUE);
void
PushCircular(QUEUE&, int);
void
PopCircular(QUEUE&, int&);
void Input(QUEUE&);
void Output(QUEUE);
Khởi tạo Queue
void Init(QUEUE& Q)
{
Q.front = 0;
Q.rear = -1;
Q.count = 0;
}
IsEmpty: Kiểm tra Queue
rỗng hay không
int
IsEmpty(QUEUE Q)
{
return (Q.count
== 0);
}
IsFull: Kiểm tra Queue
đầy hay không
int IsFull(QUEUE Q)
{
return (Q.count
== MAX);
}
EnQueue: Thêm phần tử
vào Queue
void
EnQueue(QUEUE& Q, int x)
{
if (IsFull(Q))
cout << "Queue
day.\n";
else
{
Q.Data[++Q.rear] =
x;
Q.count++;
}
}
DeQueue: Lấy phần tử ra
khỏi Queue
void
DeQueue(QUEUE& Q, int& saved)
{
if (IsEmpty(Q))
cout << "Queue
rong.\n";
else
{
saved = Q.Data[Q.front];
for (int i = Q.front;
i < Q.rear; i++)
{
Q.Data[i]
= Q.Data[i + 1];
}
Q.rear--;
Q.count--;
}
}
PushCircular: Thêm phần
tử vào Hàng đợi vòng (Queue Circular)
void
PushCircular(QUEUE& Q, int x)
{
if (IsFull(Q))
cout << "Queue
day.\n";
else
{
Q.Data[(++Q.rear) %
MAX] = x;
Q.count++;
}
}
PopCircular: Lấy phần tử
ra khỏi Hàng đợi vòng (Queue Circular)
void
PopCircular(QUEUE& Q, int& saved)
{
if (IsEmpty(Q))
cout << "Queue
rong.\n";
else
{
saved = Q.Data[Q.front];
Q.front =
(Q.front++) % MAX;
Q.count--;
}
}
Hàm nhập
void Input(QUEUE& Q)
{
int n;
int x;
do
{
cout << "Nhap
so phan tu cua Queue: ";
cin >> n;
} while (n<1 || n>MAX);
for (int i = 0;
i < n; i++)
{
cout << "Nhap
phan tu thu " << i << ":
";
cin >> x;
EnQueue(Q, x);
}
}
Hàm xuất
void Output(QUEUE Q)
{
if (IsEmpty(Q))
cout << "Queue
rong.\n";
else
{
cout << "Xuat
Queue: ";
for (int i = Q.front;
i <= Q.rear; i++)
{
cout << Q.Data[i]
<< " ";
}
cout << endl;
}
}
Main.cpp
int main()
{
QUEUE Q;
Init(Q);
Input(Q);
Output(Q);
cout << "\n1.
Kiem tra Queue co rong khong.";
cout << "\n2.
Kiem tra Queue co day khong.";
cout << "\n3.
Push phan tu vao cuoi Queue.";
cout << "\n4.
Pop phan tu o dau Queue.";
cout << "\n5.
Xuat Queue.";
cout << "\n6.
Thoat.";
cout << endl;
while (true)
{
int
luachon;
do {
cout << "\nNhap
lua chon: ";
cin >>
luachon;
switch
(luachon)
{
case 1:
{
if
(IsEmpty(Q))
cout << "Queue
rong.\n";
else cout << "Queue
khong rong.\n";
break;
}
case 2:
{
if
(IsFull(Q))
cout << "Queue
day.\n";
else cout << "Queue
khong day.\n";
break;
}
case 3:
{
int x;
cout << "Nhap
gia tri phan tu can push vao Queue: ";
cin >> x;
EnQueue(Q, x);
Output(Q);
break;
}
case 4:
{
int saved;
DeQueue(Q, saved);
cout << "Phan
tu da pop: " << saved << endl;
Output(Q);
break;
}
case 5:
{
Output(Q);
break;
}
case 6:
{
exit(1);
break;
}
}
} while
(luachon <0 || luachon>7);
}
system("pause");
return 0;
}
Nhận xét
Đăng nhận xét