顺序队列基本操作的实现

顺序队列和前面的顺序表一样,相当于一个数组,不同的是它的有效区间,当数组走到最大时,又会从头开始,这里用head 和tail两个下标来表示头和尾,即当tail到达size时,tail又从0开始,head也是同样的道理;

代码如下:

seqqueue.h

#pragma once

#define SeqQueueMaxSize 1000

typedef char SeqQueueType;

typedef struct SeqQueue{
	SeqQueueType data[SeqQueueMaxSize];
	size_t head;
	size_t tail;
	size_t size;
}SeqQueue;
//初始化
void SeqQueueInit(SeqQueue* q);
//销毁
void SeqQueueDestroy(SeqQueue* q);
//入队列
void SeqQueuePush(SeqQueue* q,SeqQueueType value);
//出队列
void SeqQueuePop(SeqQueue* q);
//去队首元素
int SeqQueueFront(SeqQueue* q, SeqQueueType* value);

seqqueue.c

#include <stdio.h>
#include <stdlib.h>
#include "seqqueue.h"

void SeqQueueInit(SeqQueue* q){
	if(q == NULL){
		//非法输入
		return;
	}
	q->size = 0;
	q->head = 0;
	q->tail = 0;
	return;
}

void SeqQueueDestroy(SeqQueue* q){
	if(q ==	NULL){
		return;
	}
	q->size = 0;
	q->head = 0;
	q->tail = 0;
	return;
}

void SeqQueuePush(SeqQueue* q,SeqQueueType value){
	if(q ==	NULL){
		return;
	}
	if(q->size >= SeqQueueMaxSize){
		//队列满了
		return;
	}
	q->data[q->tail] = value;
	q->tail++;
	if(q->tail >= SeqQueueMaxSize){
		q->tail = 0;
	}
	q->size++;
	return;
}

void SeqQueuePop(SeqQueue* q){
	if(q == NULL){
		//非法输入
		return;
	}
	if(q->size == 0){
		//空队列
		return;
	}
	q->head++;
	if(q->head >= SeqQueueMaxSize){
		q->head = 0;
	}
	q->size--;
	return;
}

int SeqQueueFront(SeqQueue* q,SeqQueueType* value){
	if(q == NULL){
		//非法输入
		return 0;
	}
	if(q->size == 0){
		//空队列
		return 0;
	}
	*value = q->data[q->head];
	return 1;
}

test.c

#include <stdio.h>
#define TEST_HEADER printf("\n==========================%s==========================\n",__FUNCTION__)

void SeqQueuePrintChar(SeqQueue* q,const char* msg){
	printf("[%s]\n",msg);
	size_t i =q-> head;
	for(i=q->head;i<q->tail;i++){
		printf("[%c] ",q->data[i]);
	}
	printf("\n");
}

void TestQueue(){
	TEST_HEADER;
	SeqQueue queue;
	SeqQueueInit(&queue);
	SeqQueuePush(&queue,'a');
	SeqQueuePush(&queue,'b');
	SeqQueuePush(&queue,'c');
	SeqQueuePush(&queue,'d');
	SeqQueuePrintChar(&queue ,"入队列四个元素");

	SeqQueuePop(&queue);
	SeqQueuePop(&queue);
	SeqQueuePrintChar(&queue,"出队列两个元素");
	SeqQueuePop(&queue);
	SeqQueuePop(&queue);
	SeqQueuePrintChar(&queue,"再出队列两个元素");

	SeqQueueType value;
	int ret = 0;
	ret = SeqQueueFront(&queue,&value);
	printf("ret expeted 1,actual %d\n",ret);
	printf("value expected a,actual %c\n",value);
}

int main(){
	TestQueue();
	return 0;
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭