//队列的C语言实现(单链表结构)
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
//单链表结点
typedef struct _QUEUE_NODE_{
int data;
struct _QUEUE_NODE_ *next;
}QUEUE_NODE;
//队列
typedef struct _QUEUE{
QUEUE_NODE *front,*rear;
int size;
}QUEUE;
//创建一个空队列
QUEUE *Create(){
QUEUE *q;
q=(QUEUE*)malloc(sizeof(QUEUE));
q->front=NULL;
q->rear=NULL;
q->size=0;
return q;
}
//插入数据到队列中
QUEUE *Insert(QUEUE *queue,int x){
QUEUE_NODE *node;
node=(QUEUE_NODE*)malloc(sizeof(QUEUE_NODE));
node->data=x;
node->next=NULL;
if(queue->rear==NULL){
queue->rear=node;
queue->front=node;
queue->size++;
}
else{
queue->rear->next=node;
queue->rear=node;
queue->size++;
}
return queue;
}
//出队
QUEUE *Delete(QUEUE *queue){
QUEUE_NODE *node;
int x;
if(queue->front==NULL){
printf("queue已经为空!");
return NULL;
}
else{
node=queue->front;
x=queue->front->data;
if(queue->front==queue->rear){
queue->front=NULL;
queue->rear=NULL;
queue->size=0;
}
else{
queue->front=queue->front->next;
queue->size--;
free(node);
}
return queue;
}
}
//判断队列是否为空,1为空,0非空
int EmptyQueue(QUEUE *queue){
if(queue->front==NULL||queue->rear==NULL){
return 1;
}
else{
return 0;
}
}
//清空队列
QUEUE *ClearQueue(QUEUE *queue){
if(queue->front==NULL){
return NULL;
}
else{
while(queue->size){
Delete(queue);
}
}
return queue;
}
//打印队列
void Printf(QUEUE *queue){
QUEUE_NODE *temp;
temp=queue->front;
while(temp!=NULL){
printf(" %d ",temp->data);
temp=temp->next;
}
printf("\n");
}
//获取队列的一个元素
int Denqueue(QUEUE *queue){
QUEUE_NODE *temp;
temp=queue->front;
if(queue!=NULL){
printf(" %d ",temp->data);
}
printf("\n");
}
int main(int argc, char *argv[]) {
QUEUE *queue;
int data;
queue=Create();
int i=0;
for(i=0;i<5;i++){
queue=Insert(queue,i);
}
printf(" %d \n",queue->size);
Printf(queue);
data=Denqueue(queue);
Delete(queue);
printf(" %d \n",queue->size);
Printf(queue);
queue=ClearQueue(queue);
printf(" %d \n",queue->size);
return 0;
}
队列的C语言实现(单链表结构)
最新推荐文章于 2022-08-24 12:24:33 发布