队列的基本操作
Posted skywalker767
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了队列的基本操作相关的知识,希望对你有一定的参考价值。
title: 队列的基本操作
mathjax: true
date: 2021-10-28 20:53:24
tags: “数据结构作业”
description: wls队列的基本操作
#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 1;
}
void QueueDestroy(struct Queue* queue)
{
struct Node* tmp;
while(queue->front)
{
tmp = queue->front;
queue->front = queue->front->next;
free(tmp);
}
}
//show all ele
int _deplay(struct Queue queue)
{
if (queue.size == 0) {
return 0;
}
struct Node *p = queue.front;
while(p)
{
printf("%d " , p -> data);
p = p -> next;
}
printf("\\n");
return 1;
}
void deplay(struct Queue queue)
{
if (_deplay(queue) == 0 )
{
printf("队列为空.\\n");
return ;
}
else {
printf("遍历结束.\\n");
}
}
void menu(struct Queue queue)
{
while(1) {
int op , x;
printf("1.插入 2.弹出\\n");
printf("3.遍历 4.销毁\\n");
printf("5.得到头元素 6.是否为空\\n");
printf("7.长度\\n");
printf("请输入操作序号:");
scanf("%d" , &op);
switch (op)
{
case 1:
printf("请输入您要插入的元素.\\n");
scanf("%d" , &x);
QueuePush(&queue, x);
break;
case 2:
if(QueuePop(&queue, &x))printf("%d 已经被弹出队列.\\n" , x);
else printf("队列已空.\\n");
break;
case 3:
deplay(queue);
break;
case 4:
QueueDestroy(&queue);
printf("已经销毁.\\n");
break;
case 5:
printf("头元素为:%d\\n" , queue.front -> data);
break;
case 6:
if(QueueEmpty(&queue)) printf("为空\\n");
else printf("不为空\\n");
break;
case 7:
printf("当前长度为:%d\\n" , queue.size);
break;
default:
printf("请输入正常的操作序号\\n");
menu(queue);
break;
}
}
}
int main(void)
{
//得到头 , 遍历 ,
struct Queue queue;
QueueInit(&queue);
menu(queue);
return 0;
}
以上是关于队列的基本操作的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段15——git命令操作一个完整流程