本帖最后由 流浪的二胡 于 2018-11-2 18:34 编辑
先放头文件:
[Asm] 纯文本查看 复制代码 #ifndef QUEUE_DAT
typedef int Item;
typedef struct node *Queue;
Queue create(void);
bool is_empty(Queue q);
bool is_full(Queue q);
void push(Queue q, Item x);
Item pop(Queue q);
void showqueue(Queue q);
#endif // !QUEUE_DAT
函数体:
[C] 纯文本查看 复制代码 #include<stdio.h>
#include<stdlib.h>
#include"queueDAT2.h"
#define MAX 10
/*定义结构体*/
struct node
{
Item *value;
int front, rear;
};
/*创建队列*/
Queue create(void)
{
Queue q;
q = (struct node *)malloc(sizeof(struct node));
q->value = (Item *)malloc(sizeof(Item));
q->front = MAX - 1;
q->rear = MAX - 1;
return q;
}
/*队空*/
bool is_empty(Queue q)
{
return q->front == q->rear;
}
/*队满*/
bool is_full(Queue q)
{
return (q->rear + 1) % MAX == q->front;
}
/*入队*/
void push(Queue q, Item x)
{
if (is_full(q))
printf("队满!");
q->rear = (q->rear + 1) % MAX;
q->value[q->rear] = x;
}
/*出队*/
Item pop(Queue q)
{
Item x;
if (is_empty(q))
printf("队空!");
q->front = (q->front + 1) % MAX;
x = q->value[q->front];
return x;
}
/*显示队列元素*/
void showqueue(Queue q)
{
int n=0,m;
while (!is_empty(q))
{
q->front = (q->front + 1) % MAX;
m = q->value[q->front];
printf(" %d ", m);
n++;
}
for (int i = 0; i < n; i++)
{
q->front = (q->front - 1) % MAX;
}
}
测试函数:
[C] 纯文本查看 复制代码 #include<stdio.h>
#include<stdlib.h>
#include"queueDAT2.h"
int main(void)
{
Queue p;
p = create();
push(p, 3);
push(p, 27);
push(p, 15);
showqueue(p);
pop(p);
printf("\n");
showqueue(p);
getchar();
}
运行结果:
|