非链表实现
#include<iostream>
#define MaxSize 50
using namespace std;
typedef int ElemType;
typedef struct Queue{
ElemType data[MaxSize];
int front;
int rear;
}Queue;
void InitQueue(Queue &Q){
Q.front = 0;
Q.rear = 0;
}
bool isEmpty(Queue Q){
if(Q.front==Q.rear)
return true;
return false;
}
//顺序队列存在假溢出现象,使用循环队列
//循环队列空出一个存储单元,来区别队满和队空的区别
bool push(Queue &Q,ElemType e){
if((Q.rear+1)%MaxSize==Q.front) //队列满
return false;
Q.data[Q.rear] = e;
Q.rear = (Q.rear+1)%MaxSize;
}
bool pop(Queue &Q,ElemType &e){
if(Q.front==Q.rear) //判断队空
return false;
e = Q.data[Q.front];
Q.front = (Q.front+1)%MaxSize;
}
int main()
{
Queue Q;
ElemType e;
InitQueue(Q);
push(Q,5);
push(Q,55);
push(Q,79);
push(Q,6);
push(Q,24);
while(!isEmpty(Q)){
pop(Q,e);
cout<<"出队元素:"<<e<<endl;
}
return 0;
}
链表实现
#include<iostream>
#include<cstdlib>
#include<cstdio>
using namespace std;
typedef int ElemType;
typedef struct Node{
ElemType data;
struct Node* next;
}*LinkNode;
typedef struct Queue{
LinkNode front;
LinkNode rear;
}Queue;
void InitQueue(Queue &Q){
Q.front=Q.rear=(LinkNode)malloc(sizeof(Node));//带头结点更方便哦
Q.front->next = NULL;
}
bool isEmpty(Queue Q){
if(Q.front==Q.rear)
return true;
return false;
}
bool push(Queue &Q,ElemType e){
LinkNode s = (LinkNode)malloc(sizeof(Node));
s->data = e;
s->next=NULL; //这是队尾所以下一个一定要指向NULL
Q.rear->next = s;
Q.rear = s;
return true;
}
bool pop(Queue &Q,ElemType &e){
if(isEmpty(Q)) return false;
LinkNode p = Q.front -> next;
e = p->data;
Q.front->next = p->next;
if(Q.rear==p)
Q.rear = Q.front;
free(p);
return true;
}
int main()
{
Queue Q;
ElemType e;
InitQueue(Q);
push(Q,5);
push(Q,3);
push(Q,6);
push(Q,8);
push(Q,99);
while(!isEmpty(Q)){
pop(Q,e);
cout<<"出队元素:"<<e<<endl;
}
return 0;
}
|