使用链表创建队列
#include<cstdio>
#include<iostream>
#include<malloc.h>
#define MAXSIZE 100
using namespace std;
typedef int datatype;
#define MAXSIZE 100
struct node
{
datatype data;
node* next;
};
typedef struct
{
node* front;
node* rear;
}sequence_queue;
//程序主体框架:
//函数名:init 参数:sequence_queue * sq
void init(sequence_queue * sq)
{
//功能: 队列初始化
sq->front = sq->rear =(node*)malloc(sizeof(node));
if (sq->front == NULL)
{
printf("out of space!!!");
}
else
sq->front->next = NULL;
}
//函数名:empty 参数:sequence_queue * sq
bool empty(sequence_queue * sq)
{
//功能: 判断队列是否为空
return sq->front == sq->rear;
}
//函数名:full 参数:sequence_queue * sq
bool full(sequence_queue * sq)
{
node* P = sq->front->next;
//功能: 判断队列是否为满
for(int i=0;i<MAXSIZE;i++){
if(P==NULL){
return true;
}
P=P->next;
}
return false;
}
//函数名:display 参数:sequence_queue * sq
void display(sequence_queue * sq)
{
//功能: 打印队列
node* P = sq->front->next;
if (empty(sq))
{
printf("Print Warning: the queue is empty !!!");
}
while (P)
{
printf("%d ", P->data);
P = P->next;
}
printf("\n");
}
//函数名:dequeue 参数:sequence_queue * sq
datatype dequeue(sequence_queue * sq)
{
//功能: 出队
node* P;
int x;
if (empty(sq))
{
printf("there is no element in the stack!!!");
}
else{
P =sq->front->next;
x=P->data;
sq->front->next =P->next;
if (P == sq->rear)//如果只有一个元素,将尾指针移到头指针。
{
sq->rear = sq->front;
}
free(P);
}
return x;
}
//函数名:insertqueue 参数:sequence_queue * sq, datatype x
void insertqueue(sequence_queue * sq, datatype x)
{
//功能: 入队
node* P = (node*)malloc(sizeof(struct node));
P->data = x;
P->next = NULL;
sq->rear->next = P;
sq->rear = P;
}
//函数名:clearqueue 参数:sequence_queue * sq
void clearqueue(sequence_queue * sq)
{
//功能: 清空队列
if (sq == NULL)
{
printf("must use creatstack first!!");
}
else
{
while (!empty(sq))
dequeue(sq);
}
}
int main()
{
datatype x;
sequence_queue* sq = (sequence_queue*)malloc(sizeof(sequence_queue));
init(sq);
int n;
printf("请输入需要创建队列的个数:");
scanf("%d", &n);
printf("请输入需要插入的值:");
for(int i = 1; i <= n; ++ i)
{
scanf("%d", &x);
insertqueue(sq, x);
}
bool flag;
do
{
printf("是否进行出队操作(1: 是, 0: 否):");
scanf("%d", &flag);
if(flag)
{
x = dequeue(sq);
printf("出队的元素为: %d\n", x);
}
display(sq);
}while(flag);
do
{
printf("是否进行插入操作(1: 是, 0: 否):");
scanf("%d", &flag);
if(flag)
{
printf("请输入需要插入的值:");
scanf("%d", &x);
insertqueue(sq, x);
}
display(sq);
}while(flag);
clearqueue(sq);
return 0;
}
//测试用例:
//5 2 5 2 9 3 1 0 1 5 0