欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

玩转循环队列:数据结构与算法的实践操作

最编程 2024-01-31 16:05:32
...
//循环队列的入队和出队算法设计 #include<iostream> #include<Windows.h> #define MaxSize 6 //定义本循环队列的最大容量 using namespace std; typedef struct _LQueue { //循环队列 int sq[MaxSize]; int front; //循环队列的前指针 int rear; //循环队列的尾指针 }LqList; //初始化循环队列 bool InitLqList(LqList *duilie) { if (!duilie) return false; duilie->front = duilie->rear = 0; return true; } //插入元素到循环队列 bool InserLq(LqList* duilie, int &Element) { if (!duilie) return false; if ((duilie->rear + 1) % MaxSize == duilie->front) { cout << "该队列元素已满! "; } else { duilie->sq[duilie->rear] = Element; duilie->rear =( duilie->rear + 1)%MaxSize; } return true; } //打印队列 void PrintLq(LqList *duilie) { if (!duilie) return; cout << "本循环队列的元素依次是: "; int i = duilie->front; while (i != duilie->rear) { cout <<" "<< duilie->sq[i]; i = (i + 1) % MaxSize; } return; } //获取循环队列的首元素,元素不出队 bool GetLqFirst(LqList *duilie, int &Element) { if (!duilie) return false; Element = duilie->sq[duilie->front]; return true; } //出队 bool outLq(LqList *duilie,int &Element){ if (!duilie) return false; if (duilie->front == duilie->rear) { cout << "该队列是空队列! "; return false; } else { Element = duilie->sq[duilie->front]; duilie->front = (duilie->front + 1) % MaxSize; } return true; } //获取循环队列元素个数 void Getlen(LqList *duilie) { cout << "循环队列的元素个数是: " << (duilie->rear - duilie->front + MaxSize) % MaxSize; return; } int main(void) { LqList *duilie =new LqList; if (InitLqList(duilie)) { cout << "初始化循环队列成功! " << endl; } else { cout << "初始化循环队列失败! " << endl; } //循环队列入队 int num; //用户想要入队或者出队的个数 cout << "请输入你想要入队的个数(本程序设置的循环队列最大容量为5): "; cin >> num; //直到用户输入正确的入队个数为止 while (1) { if (num > MaxSize) { cout << "输入的数量超过了本队列的最大容量,请重新输入入队的个数: " << endl; cout << "请输入你想要入队的个数: "; cin >> num; } else { break; } } int Element = 0; for (int i = 0; i < num; i++) { cout << "请输入你想要插入的元素: "; cin >> Element; if (InserLq(duilie,Element)) { cout << "插入元素 " << Element << " 成功! " << endl; } else { cout << "插入元素失败! " << endl; } } //打印循环队列里的元素 PrintLq(duilie); //获取循环队列的首元素,元素不出列 if (GetLqFirst(duilie,Element)) { cout << "循环队列的首元素是: " << Element << endl; } else { cout << "获取循环队列首元素失败! " << endl; } //循环队列出队 cout << "请输入你想要出队的个数: "; cin >> num; cout << endl; //直到用户输入正确的出队个数为止 while (1) { if (num > (duilie->rear - duilie->front + MaxSize) % MaxSize) { cout << "输入的数量超过了本队列的最大容量,请重新输入出队的个数: " << endl; cout << "请输入你想要出队的个数: "; cin >> num; } else { break; } } for (int i = 0; i < num; i++) { if (outLq(duilie, Element)) { cout << "循环队列元素出队成功! 出队元素是: " << Element << endl; } else { cout << "循环队列元素出队失败! " << endl; } } PrintLq(duilie); Getlen(duilie); cout << "在入队一个元素吧,这可是循环队列哟!" << endl; cout << "请输入你想要插入的元素: "; cin >> Element; if (InserLq(duilie, Element)) { cout << "插入元素 " << Element << " 成功! " << endl; } else { cout << "插入元素失败! " << endl; } PrintLq(duilie); system("pause"); return 0; }

推荐阅读