链队列的入队、出队算法

#include<stdio.h>
#include<stdlib.h>

typedef struct Qnode  
{
	int data;
	struct Qnode *next; 
}Qnode;  

typedef struct
{
	struct Qnode *front;
	struct Qnode *rear;
}LinkQueue;

LinkQueue *Q;

int main()
{
	void EnQueue(int e);
	int DeQueue();
	int i;
	Q = (LinkQueue *)malloc(sizeof(LinkQueue));
	Q->front = (Qnode *)malloc(sizeof(Qnode));
	Q->rear = Q->front;
	for(i=0; i<10; i++)
		EnQueue(i);
	printf("pop first 5 elements\n");
	for(i=0; i<5; i++)
		printf("The %d element is %d\n",i+1,DeQueue());   
	return 0;
}

void EnQueue(int e)
{
	Qnode *p;
	p = (Qnode *)malloc(sizeof(Qnode));
	if(!p)
		exit(1);  //存储分配失败
	p->data = e;
	p->next = NULL;
	(*Q).rear->next = p;
	(*Q).rear = p;
}

int DeQueue()
{
	Qnode *p;
	int e;
	if(Q->front == Q->rear)  //空队列
		exit(1);
	p = (*Q).front->next;  //删除p结点(队头),Q->front不作为删除对象
	e = p->data;
	(*Q).front->next = p->next;
	if((*Q).rear == p)
		(*Q).rear = (*Q).front;
	free(p);
	return e;
}

程序运行结果
在这里插入图片描述
如果感觉不错,那就给我点个赞吧(ノ ̄▽ ̄)


版权声明:本文为weixin_45634365原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。