循环队列
代码如下:
#include "pch.h" #include <iostream> using namespace std; #define MAXSIZE 5 struct SqQueue { char* Base; int front; int rear; }; //初始化循环队列 int initqueue(SqQueue &q) { q.Base = new char[MAXSIZE]; if (!q.Base) { cout << "内存空间分配失败!" << endl; return 0; } q.front = q.rear = 0; return 1; } //求循环队列的长度 int getqueuelength(SqQueue q) { return (q.rear - q.front + MAXSIZE) % MAXSIZE; } //求循环队列的头元素 char getqueuehead(SqQueue q) { return q.Base[q.front]; //q.front 是下标位置 } //循环队列的入队 int insertqueue(SqQueue &q, char e) { if ((q.rear+1)%MAXSIZE==q.front)//这样队列就满了 { cout << "队列已满,无法继续插入队列!" << endl; return 0; } q.Base[q.rear] = e; q.rear = (q.rear + 1) % MAXSIZE; cout << "入队列成功!" << endl; return 1; } //循环队列的出队列 int outputqueue(SqQueue &q, char e) { if (q.rear==q.front) { cout << "队列为空,无法出队列!" << endl; return 0; } e=q.Base[q.front]; q.front = (q.front + 1) % MAXSIZE; cout << "出队列成功!" << endl; return 1; } int main() { SqQueue q; initqueue(q); insertqueue(q, 'a'); insertqueue(q, 'b'); insertqueue(q, 'c'); cout << getqueuehead(q) << endl;; char c='a'; outputqueue(q,c); cout << getqueuehead(q) << endl; outputqueue(q, c); cout << getqueuehead(q) << endl; cout << "循环队列的长度为:" << getqueuelength(q) << endl; return 0; }
结果为:
链队列
代码如下:
#include "pch.h" #include <iostream> using namespace std; //链队列 typedef struct qnode { char data; qnode *next; }*queueper; //头指针和尾指针 struct linkqueue { queueper front; //队列的尾指针 queueper rear; //队列的头指针 }; //初始化队列 int initlinkqueue(linkqueue &q) { //创建新节点设置为头,队尾队头志向该节点 q.front = q.rear = new qnode; q.rear->next = NULL;//头结点指针域设置为空 return 0; } //获取队列的头元素 char getqueueHead(linkqueue q) { if (q.front!=q.rear) { return q.front->next->data; } } //链队列入队列 int insertelem(linkqueue &q,char e) { queueper p; p = new qnode; p->data = e; p->next = NULL; q.rear->next = p; //将新节点插入到队列的尾部(后插法) q.rear = p; //尾指针指向尾结点 cout << "队列入队成功!" << endl; return 0; } //链队列出队列 int outputqueue(linkqueue &q, char &e) { queueper p; if (q.rear==q.front) { cout << "队列为空,无法出队列!" << endl; return 0; } p = q.front->next; //指向队头元素 e = p->data; //得到队头元素的数据域 q.front->next = p->next;//修改头指针 if (q.front==p) { q.rear = q.front; } delete p; cout << "出队列成功!" << endl; return 1; } int main() { linkqueue q; initlinkqueue(q); insertelem(q, 'a'); insertelem(q, 'b'); insertelem(q, 'c'); insertelem(q, 'd'); cout << "队列的头元素为:" << getqueueHead(q) << endl; char e = 'a'; outputqueue(q, e); cout << "队列的头元素为:" << getqueueHead(q) << endl; outputqueue(q, e); cout << "队列的头元素为:" << getqueueHead(q) << endl; return 0;
结果为: