队列(链式存储)

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

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

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

void InitQueue(LinkQueue &);	//初始化
bool IsEmpty(LinkQueue);	//判空 
void EnQueue(LinkQueue & , int);	//入队 
void DeQueue(LinkQueue & , int *);	//出队 

void Print(LinkQueue);	//用于查看当前链表 

int main(void){
	LinkQueue Q;
	InitQueue(Q);

	int a = 0;

	EnQueue(Q,1);
	EnQueue(Q,2);
	EnQueue(Q,3);
	EnQueue(Q,4);
	Print(Q);
	
	printf("
"); 
	
	DeQueue(Q,&a);		//未对队列为空输入进行处理 
	printf("当前出对队列元素:%d
",a);
	DeQueue(Q,&a);
	printf("当前出对队列元素:%d
",a);
	Print(Q);
	return 0;
}

void InitQueue(LinkQueue &Q){	//初始化
	Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
	Q.front->next = NULL;
}

bool IsEmpty(LinkQueue Q){	//判空
	if(Q.front == Q.rear){
		return true;
	}else{
		return false;
	}
}

void EnQueue(LinkQueue &Q , int x){	//入队 
	LinkNode *s = (LinkNode*)malloc(sizeof(LinkNode));
	s->data = x;
	s->next = Q.rear->next;
	Q.rear->next = s;
	Q.rear = s;
}

void DeQueue(LinkQueue &Q , int *x){	//出队 
	if(IsEmpty(Q)){
		printf("当前队列为空,出队失败!");
		return;
	}
	LinkNode *s = Q.front->next;
	*x = s->data;
	Q.front->next = s->next;
	if(s == Q.rear){	///判断是否为最后一个出队的元素 
		Q.rear = Q.front;
	}
	free(s);
}

void Print(LinkQueue Q){
	LinkNode *p = Q.front->next;
	printf("当前队列为:");
	while(p){
		printf("%d ",p->data);
		p = p->next;
	}
}

示例截图

原文地址:https://www.cnblogs.com/Timesi/p/14315345.html