C++ 程式來實現佇列
佇列
佇列(以先進先出 First-in–first-out, FIFO 實現),從一端(後)進行插入,從另一端(前)進行刪除。首先進入的元素先被刪除。
佇列操作包括:−
EnQueue (int data) − 從後端插入
int DeQueue()− 從前端刪除
這是一個 C++ 程式,使用陣列來實現佇列。
演算法
Begin function Enqueue() to insert elements in queue: If queue is completely filled up then print “Overflow”. Otherwise insert element at rear. Update the value of rear End Begin function Dequeue() to delete elements from queue: If queue is completely empty then print “Underflow”. Otherwise insert element from the front. Update the value of rear. End
示例程式碼
#include <bits/stdc++.h>
using namespace std;
struct Q {
int f, r, capacity;
int* q;
Q(int c) {
f = r= 0;
capacity = c;
q = new int;
}
~Q() { delete[] q; }
void Enqueue(int d) {
if (capacity == r) { //check if queue is empty or not
printf("\nQueue is full\n");
return;
} else {
q[r] = d; //insert data
r++; //update rear
}
return;
}
void Dequeue() {
if (f == r) {
printf("\nQueue is empty\n");
return;
} else {
for (int i = 0; i < r - 1; i++) {
q[i] = q[i + 1];
}
r--; //update rear
}
return;
}
void Display() //display the queue {
int i;
if (f == r) {
printf("\nQueue is Empty\n");
return;
}
for (i = f; i < r; i++) {
printf(" %d <-- ", q[i]);
}
return;
}
void Front() {
if (f == r) {
printf("\nQueue is Empty\n");
return;
}
printf("\nFront Element is: %d", q[f]); //print front element of queue
return;
}
};
int main(void) {
Q qu(3);
qu.Display();
cout<<"after inserting elements"<<endl;
qu.Enqueue(10);
qu.Enqueue(20);
qu.Enqueue(30);
qu.Display();
qu.Dequeue();
qu.Dequeue();
printf("\n\nafter two node deletion\n\n");
qu.Display();
qu.Front();
return 0;
}輸出
Queue is Empty 10 <-- 20 <-- 30 <-- after two node deletion 30 <-- Front Element is: 30
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP