#include<stdio.h>
#define false 0
#define ok 1
//定义队列每个节点的结构
typedef struct node
{
int data;
struct node *next;
}node,*qnode;//相当于typedef struct node * qnode;
//定义整个队列结构
typedef struct squeue
{
qnode front, rear;
}squeue;
//建立一个空的队列
void initqueue(squeue *l)
{
l->front=(qnode)malloc(sizeof(node));
l->rear=(qnode)malloc(sizeof(node));
l->front->next = NULL;
l->rear->next = NULL;
}
//入队列
void inqueue(squeue *l, int e)
{
qnode s=(qnode)malloc(sizeof(node));
s->data = e;
s->next = NULL;
if (l->front->next == NULL)
{
l->front->next = s;
l->rear = s;
}
else
{
l->rear->next = s;
l->rear = s;
}
}
//出队列
int outqueue(squeue *l, int *e)
{
if (l->front == l->rear)
return false;
qnode s= l->front->next;
*e = s->data;
l->front->next = s->next;
if (l->rear == s) //如果删除的是尾节点,此时队列为空
l->rear = l->front;
free(s);
return ok;
}
//查看队列
void seequeue(squeue l)
{
if (l.rear == l.front)
printf("队列为空");
qnode s= l.front->next;
while (s)
{
printf("%4d", s->data);
s = s->next;
}
free(s);
}
int main(void)
{
int a;
squeue q;
initqueue(&q);
inqueue(&q, 2);
inqueue(&q, 3);
seequeue(q);
outqueue(&q, &a);
seequeue(q);
outqueue(&q, &a);
seequeue(q);
return 0;
}
定义了一个队列结构,front作为头指针,front->next指向队列头,rear指向队列尾。
一开始调试一直出错是在入队列时忘了对队列是否为空进行判断,第一个元素插入的方法和以后的元素不一样,第一个元素需要让front->next指向它,rear直接指向它。
刚申明的指针要指向null,后面再让它保存的地址更改,在windows中指针p指向null相当于p的值为0。