赞
踩
一维数组在实现队列的时候会发生假溢出,此时我们需要用到循环队列。以下是一个粗略但是完整的代码。
- /* 数组实现循环队列 */
- #include <stdio.h>
- #include <stdlib.h>
- #include <iostream>
- using namespace std;
- #define MAX 6
-
- typedef struct{
- int* data;
- int front;
- int rear;
- }Queue;
-
- void init_queue(Queue &Q)//队列初始化
- {
- Q.data = (int*)malloc(sizeof(int)*MAX);
- Q.front = 0;
- Q.rear = 0;
- }
-
- bool empty_queue(Queue Q)//判空
- {
- return Q.front==Q.rear;
- }
-
- bool full_queue(Queue Q)///判队满
- {
- return (Q.rear+1)%MAX==Q.front;
- }
-
- bool push_queue(Queue &Q,int e)//入队
- {
- if(full_queue(Q)) return false;
- *(Q.data+Q.rear) = e;
- Q.rear = (Q.rear+1) % MAX;
- return true;
- }
-
- bool pop_queue(Queue &Q,int &e)//出队
- {
- if(empty_queue(Q)) return false;
- e = *(Q.data+Q.front);
- Q.front = (Q.front+1) % MAX;
- return true;
- }
-
- void print_queue(Queue Q)//打印队列
- {
- for (int i=Q.front;i!=Q.rear;i=(i+1)%MAX){
- cout << *(Q.data+i) << " ";
- }
- cout << endl;
- }
-
- int main()
- {
- Queue Q;
- char s;
- int e;
- init_queue(Q);
-
- while (1){
- cout << "i for insert and p for pop" << endl;
- cin >> s;
- if (s == 'i'){
- cout << "enter the element" << endl;
- cin >> e;
- if (push_queue(Q,e) == true) print_queue(Q);
- else{
- cout << "the queue is full" << endl;
- }
- }
- else if(s == 'p'){
- if (pop_queue(Q,e)==true) {
- cout << "the element poped is " << e << endl;
- print_queue(Q);
- }
- else {
- cout << "the queue is empty" << endl;
- }
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。