#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
struct Node
{
int data;
struct Node* next;
};
struct Queue
{
struct Node* front;
struct Node* rear;
int size;
};
void QueueInit(struct Queue* queue)
{
queue->front = NULL;
queue->rear = NULL;
queue->size = 0;
}
int QueueEmpty(struct Queue* queue)
{
return (queue->size == 0);
}
void QueuePush(struct Queue* queue, const int data)
{
struct Node* node;
node = (struct Node*)malloc(sizeof(struct Node));
assert(node != NULL);
node->data = data;
node->next = NULL;
if(QueueEmpty(queue))
{
queue->front = node;
queue->rear = node;
}
else
{
queue->rear->next = node;
queue->rear = node;
}
++queue->size;
}
int QueuePop(struct Queue* queue, int* data)
{
if (QueueEmpty(queue))
{
return 0;
}
struct Node* tmp = queue->front;
*data = queue->front->data;
queue->front = queue->front->next;
free(tmp);
--queue->size;
return *data;
}
void ClearQueue(struct Queue* queue){
struct Node* tmp;
while(queue->front!=queue->rear)
{
tmp = queue->front;
queue->front = queue->front->next;
queue->size--;
free(tmp);
}
queue->front=queue->rear=NULL;
}
void QueueDestroy(struct Queue* queue)
{
struct Node* tmp;
while(queue->front)
{
tmp = queue->front;
queue->front = queue->front->next;
queue->size--;
free(tmp);
}
}
void GetHead(struct Queue* queue){
struct Node* p=queue->front;
printf("队头元素为:%d\n",p->data);
}
int GetLen(struct Queue* queue){
return queue->size;
}
void print(struct Queue* queue){
int len = GetLen(queue)+1;
struct Node* p=queue->front;
printf("此时队列中元素为:");
while (len)
{
printf("%d ", p->data);
p=p->next;
len--;
}
printf("\n");
}
void menu(){
printf("-----------------------------\n");
printf("-1.清空队列 2.销毁队列-\n");
printf("-3.入队 4.出队-----\n");
printf("-5.获取队头元素 6.遍历输出-\n");
printf("-7.获取队列长度 8.正常退出-\n");
printf("-----------------------------\n");
}
int main(void)
{
struct Queue queue;
QueueInit(&queue);
while(1){
menu();
printf("请输入选项:\n");
int option;
scanf("%d",&option);
if(option==8) break;
switch(option){
case 1:ClearQueue(&queue);break;
case 2:QueueDestroy(&queue);break;
case 3:
int n;
printf("请输入要存入数字的个数及数字:\n");
scanf("%d",&n);
for(int i=0;i<n;i++){
int j;
scanf("%d",&j);
QueuePush(&queue, j);
}
break;
case 4:
int i;
QueuePop(&queue,&i);
break;
case 5:GetHead(&queue);break;
case 6:print(&queue);break;
case 7:
int len = GetLen(&queue);
printf("队列长度为:%d\n",len);
break;
}
}
return 0;
}