队列的概念及其接口实现
队列:只允许在队尾插入数据,在队头删除数据,遵循先进先出(First in First out)的原则
队列的实现:相对而言,队列用链表实现更优一些。
接口实现:
#define _CRT_SECURE_NO_WARNINGS 1
#ifndef Queue_H
#define Queue_H
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <malloc.h>
typedef int QUDataType;
typedef struct QueueNode
{
struct QueueNode* _next;
QUDataType _data;
}QueueNode;
typedef struct Queue
{
QueueNode* _head;
QueueNode* _tail;
}Queue;
void QueueInit(Queue* pq);
void QueueDestory(Queuepq);
void test();
QueueNode BuyQueueNode(QUDataType x);
void print(Queue* pq);
void QueuePush(Queue* pq, QUDataType x);
void QueuePop(Queue* pq);
QUDataType QueueFront(Queue* pq);
QUDataType QueueBack(Queue* pq);
int QueueSize(Queue* pq);
int QueueEmpty(Queue* pq);
int QueueSize(Queue* pq);
#endif //Queue_H
#include “Queue.h”
void QueueInit(Queue* pq)
{
assert(pq);
//pq->_head = NULL;
pq->_tail = NULL;//
pq->_head = (QueueNode*)malloc(sizeof(QueueNode));
assert(pq->_head);
pq->_tail = pq->_head;
pq->_head->_next = NULL;
}
void test()
{
Queue q;
QueueInit(&q);
QueueDestory(&q);
BuyQueueNode(2);
print(&q);
QueuePush(&q, 1);
QueuePush(&q, 2);
QueuePush(&q, 3);
QueuePush(&q, 4);
print(&q);
printf("\n");
/QueuePop(&q);
print(&q);
printf("\n");
printf("%d “, QueueFront(&q));
printf(”\n");
printf("%d ", QueueBack(&q));
QueueEmpty(&q);/
printf("%d ",QueueSize(&q));
}
void print(Queue* pq)
{
QueueNode* cur = pq->_head->_next;
assert(pq);
while (cur!=NULL)
{
printf("%d ", cur->_data);
cur = cur->_next;
}
}
void QueueDestory(Queue* pq)
{
assert(pq);
QueueNode* cur = pq->_head->_next;
while (cur!= NULL)
{
QueueNode* next = cur->_next;
free(cur);
cur = next;
}
free(cur);
}
QueueNode* BuyQueueNode(QUDataType x)
{
QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
assert(newnode);
newnode->_data = x;
newnode->_next = NULL;
return newnode;
}
void QueuePush(Queue* pq, QUDataType x)
{
assert(pq);
QueueNode* newnode = BuyQueueNode(x);
assert(newnode);
//if (pq->_head == NULL)
//{
// /*QueueNode* head = BuyQueueNode(x);*/
// pq->_tail = newnode;
// pq->_head = newnode;
// /*head->_data = x;*/
//}
///*newnode->_data = x;
//newnode->_next = NULL;*/
//pq->_tail->_next = newnode;
//pq->_tail = newnode;
newnode->_data = x;
newnode->_next = NULL;
pq->_tail->_next = newnode;
pq->_tail = newnode;
}
void QueuePop(Queue* pq)
{
assert(pq);
QueueNode* cur = pq->_head;
QueueNode* next = cur->_next;
free(cur);
pq->_head = next;
}
QUDataType QueueFront(Queue* pq)
{
assert(pq);
return pq->_head->_next->_data;
}
QUDataType QueueBack(Queue* pq)
{
assert(pq);
return pq->_tail->_data;
}
int QueueEmpty(Queue* pq)
{
if (pq->_head == pq->_tail)
return 0;
return 1;
}
int QueueSize(Queue* pq)
{
size_t size = 0;
if (QueueEmpty(pq) == 0)
return 0;
else
{
QueueNode* cur = pq->_head;
while (cur->_next)
{
size++;
cur = cur->_next;
}
return size;
}
}