#pragma once #include运行结果using namespace std; #define MAXSIZE 10 //顺序队类型定义 typedef struct { int *base; int front;// 队首指针 int rear;// 队尾指针 } SqQueue; //初始化队列 void initQueue(SqQueue& Q) { Q.base = new int[MAXSIZE]; // 队首和队尾指针重合并指向0 Q.front = Q.rear = 0; } //入队(从队头插入 void enQueue(SqQueue& Q, int e) { // 队满 if (Q.front == (Q.rear + 1 + MAXSIZE) % MAXSIZE) { cout << "队满!" << endl; exit(0); } else { //注意:这里是先入队,再修改指针 Q.base[Q.front] = e; Q.front = (Q.front - 1 + MAXSIZE) % MAXSIZE; } } //出队(从队尾出队) int deQueue(SqQueue& Q, int& e) { // 队空 if (Q.rear == Q.front) { cout << "队空!" << endl; exit(0); } else { //先入队,再修改指针 e = Q.base[Q.rear]; Q.rear = (Q.rear - 1 + MAXSIZE) % MAXSIZE; return e; } } //打印队列 void printQueue(SqQueue Q) { //不为空 while (Q.rear != Q.front) { Q.front = (Q.front + 1) % MAXSIZE; cout << Q.base[Q.front] << " "; } cout << endl; } int main() { SqQueue Q; initQueue(Q); int nums[] = { 1,2,3,4,5,6 }; int len = sizeof(nums) / sizeof(int); // 将数组中的元素入队 for (int i = 0; i < len; i++) { enQueue(Q, nums[i]); } // 打印队列 printQueue(Q); // 将元素1出队 int e; deQueue(Q, e); // 打印队列 printQueue(Q); system("pause"); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)