Queue.h
#pragma once
#include <malloc.h>
#include <assert.h>
#include <stdio.h>
typedef int QDataType;
typedef struct QListNode
{
struct QListNode* next;
QDataType data;
}QNode;
typedef struct Queue
{
QNode* front;
QNode* back;
int size;
}Queue;
void QueueInit(Queue* ps);
void QueuePush(Queue* ps, QDataType data);
void QueuePop(Queue* ps);
QDataType QueueFront(Queue* ps);
QDataType QueueBack(Queue* ps);
int QueueSize(Queue* ps);
int QueueEmpty(Queue* ps);
void QueueDestroy(Queue* ps);
Queue.c
#include"Queue.h"
QNode* buynode(QDataType data){
QNode* newnode = (QNode*)malloc(sizeof(QNode));
newnode->data = data;
newnode->next = NULL;
return newnode;
}
void QueueInit(Queue* ps){
assert(ps);
ps->back = ps->front = NULL;
ps->size = 0;
}
void QueuePush(Queue* ps, QDataType data){
assert(ps);
QNode* newnode = buynode(data);
if (ps->front == NULL){
ps->front = newnode;
}
else{
ps->back->next = newnode;
}
ps->back = newnode;
ps->size++;
}
void QueuePop(Queue* ps){
assert(ps);
if (QueueEmpty(ps)){
return;
}
else{
QNode* delNode = ps->front;
ps->front = delNode->next;
free(delNode);
if (NULL == ps->front)
{
ps->back = NULL;
}
}
ps->size--;
}
QDataType QueueFront(Queue* ps){
assert(!QueueEmpty(ps));
return ps->front->data;
}
QDataType QueueBack(Queue* ps){
assert(!QueueEmpty(ps));
return ps->back->data;
}
int QueueSize(Queue* ps){
assert(!QueueEmpty(ps));
return ps->size;
}
int QueueEmpty(Queue* ps){
assert(ps);
return NULL == ps->front;
}
void QueueDestroy(Queue* ps){
assert(ps);
QNode* cur = ps->front;
while (cur){
ps ->front= cur->next;
free(cur);
cur = ps->front;
}
ps->back = NULL;
ps->size = 0;
}
test.c
#include"Queue.h"
void test(){
Queue ps;
QueueInit(&ps);
QueuePush(&ps, 1);
QueuePush(&ps, 2);
QueuePush(&ps, 3);
printf("%d\n", QueueSize(&ps));
printf("%d\n", QueueFront(&ps));
QueuePop(&ps);
QueuePop(&ps);
QueuePop(&ps);
QueuePop(&ps);
QueuePop(&ps);
QueueDestroy(&ps);
}
int main(){
test();
system("pause");
return 0;
}
|