队列的实现
程序员文章站
2022-03-08 09:18:09
...
main.c
文件
#include"Queue.h"
int main()
{
QueueTest();
system("pause");
return 0;
}
Queue.h
文件
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<assert.h>
typedef int QUDataType;
typedef struct QueueNode
{
QUDataType _data;
struct QueueNode *_next;
}QueueNode;
typedef struct Queue
{
QueueNode *_front;
QueueNode *_rear;
}Queue;
void QueueInit(Queue *q);
void QueueDestory(Queue *q);
void QueuePush(Queue *q, QUDataType x);
void QueuePop(Queue *q);
int QueueSize(Queue *q);
int QueueEmpty(Queue *q);
QUDataType QueueFront(Queue *q);
QUDataType QueueRear(Queue *q);
void QueueTest();
Queue.c
文件
#include"Queue.h"
void QueueInit(Queue *q)
{
assert(q);
q->_front = q->_rear = NULL;
}
void QueueDestory(Queue *q)
{
assert(q);
QueueNode * cur = q->_front;
while (cur)
{
QueueNode * next = cur->_next;
free(cur);
cur = next;
}
}
void QueuePush(Queue *q, QUDataType x)
{
assert(q);
//申请结点
QueueNode *newNode = (QueueNode*)malloc(sizeof(QueueNode));
newNode->_data = x;
//连接到队尾1.空队列2.有数据
if (q->_front == NULL)
{
q->_front = q->_rear = newNode;
q->_rear->_next = NULL;
}
else
{
q->_rear->_next = newNode;
q->_rear = q->_rear->_next;
q->_rear->_next = NULL;
}
}
void QueuePop(Queue *q)
{
assert(q);
//空队列不能删除
if(q->_front)
{
QueueNode *next = q->_front->_next;
free(q->_front);
q->_front = next;
}
}
int QueueSize(Queue *q)
{
assert(q);
QueueNode *cur = q->_front;
int size = 0;
while (cur)
{
size++;
cur = cur->_next;
}
return size;
}
int QueueEmpty(Queue *q)
{
assert(q);
if (q->_front == NULL)
{
return 0;
}
else
{
return 1;
}
}
QUDataType QueueFront(Queue *q)
{
assert(q);
return q->_front->_data;
}
QUDataType QueueRear(Queue *q)
{
assert(q);
return q->_rear->_data;
}
void QueueTest()
{
Queue qu;
QueueInit(&qu);
QueuePush(&qu, 1);
QueuePush(&qu, 2);
QueuePush(&qu, 3);
QueuePush(&qu, 4);
QueuePush(&qu, 5);
printf("Empty:%d\n", QueueEmpty(&qu));
printf("Size:%d\n", QueueSize(&qu));
while (qu._front!=NULL)
{
printf("Front=%d\n", QueueFront(&qu));
QueuePop(&qu);
}
printf("Empty:%d\n", QueueEmpty(&qu));
printf("Size:%d\n", QueueSize(&qu));
QueueDestory(&qu);
}
上一篇: Ubuntu新用户
下一篇: php最简单的文件处理。