C ++程序使用数组实现队列
队列是包含元素集合的抽象数据结构。队列执行FIFO机制,即,首先插入的元素也将首先删除。换句话说,最近最少添加的元素首先在队列中被删除。
使用数组实现队列的程序如下:
示例
#include <iostream> using namespace std; int queue[100], n = 100, front = - 1, rear = - 1; void Insert() { int val; if (rear == n - 1) cout<<"Queue Overflow"<<endl; else { if (front == - 1) front = 0; cout<<"Insert the element in queue : "<<endl; cin>>val; rear++; queue[rear] = val; } } void Delete() { if (front == - 1 || front > rear) { cout<<"Queue Underflow "; return ; } else { cout<<"Element deleted from queue is : "<< queue[front] <<endl; front++;; } } void Display() { if (front == - 1) cout<<"Queue is empty"<<endl; else { cout<<"Queue elements are : "; for (int i = front; i <= rear; i++) cout<<queue[i]<<" "; cout<<endl; } } int main() { int ch; cout<<"1) Insert element to queue"<<endl; cout<<"2) Delete element from queue"<<endl; cout<<"3) Display all the elements of queue"<<endl; cout<<"4) Exit"<<endl; do { cout<<"Enter your choice : "<<endl; cin<<ch; switch (ch) { case 1: Insert(); break; case 2: Delete(); break; case 3: Display(); break; case 4: cout<<"Exit"<<endl; break; default: cout<<"Invalid choice"<<endl; } } while(ch!=4); return 0; }
上面程序的输出如下
1) Insert element to queue 2) Delete element from queue 3) Display all the elements of queue 4) Exit Enter your choice : 1 Insert the element in queue : 4 Enter your choice : 1 Insert the element in queue : 3 Enter your choice : 1 Insert the element in queue : 5 Enter your choice : 2 Element deleted from queue is : 4 Enter your choice : 3 Queue elements are : 3 5 Enter your choice : 7 Invalid choice Enter your choice : 4 Exit
在上面的程序中,该函数Insert()
将元素插入队列。如果后方等于n-1,则队列已满,并显示溢出。如果front为-1,则将其递增1。然后,Rear将其递增1,并将元素插入back的索引中。这如下所示-
void Insert() { int val; if (rear == n - 1) cout<<"Queue Overflow"<<endl; else { if (front == - 1) front = 0; cout<<"Insert the element in queue : "<<endl; cin>>val; rear++; queue[rear] = val; } }
在函数中Delete()
,如果队列中没有元素,则为下溢状态。否则,将显示前面的元素,并且前面的元素将增加一。这如下所示-
void Delete() { if (front == - 1 || front > rear) { cout<<"Queue Underflow "; return ; } else { cout<<"Element deleted from queue is : "<< queue[front] <<endl; front++;; } }
在函数中display()
,如果front为-1,则队列为空。否则,将使用for循环显示所有队列元素。这如下所示-
void Display() { if (front == - 1) cout<<"Queue is empty"<<endl; else { cout<<"Queue elements are : "; for (int i = front; i <= rear; i++) cout<<queue[i]<<" "; cout<<endl; } }
main()
如果用户要插入,删除或显示队列,该功能将为用户提供一个选择。根据用户响应,使用开关调用适当的功能。如果用户输入无效的响应,则将其打印出来。下面的代码片段如下-
int main() { int ch; cout<<"1) Insert element to queue"<<endl; cout<<"2) Delete element from queue"<<endl; cout<<"3) Display all the elements of queue"<<endl; cout<<"4) Exit"<<endl; do { cout<<"Enter your choice : "<<endl; cin>>ch; switch (ch) { case 1: Insert(); break; case 2: Delete(); break; case 3: Display(); break; case 4: cout<<"Exit"<<endl; break; default: cout<<"Invalid choice"<<endl; } } while(ch!=4); return 0; }