基于顺序表的队列基本操作实现

程序代码:

#include
#include
#define SeqQueueType char

#define SeqQueueMax 1000

typedef struct Queue{
SeqQueueType data[SeqQueueMax];
size_t head;
size_t tail;
size_t size;
} SeqQueue;
//顺序队列的初始化
void SeqQueueInit(SeqQueue* seq){
if(seq == NULL){
return;
}
seq->head = 0;
seq->tail = 0;
seq->size = 0;
}


//顺序队列到入队
void SeqQueuePush(SeqQueue* seq,SeqQueueType value){
if(seq == NULL){
return;
}
seq->data[seq->tail] = value;
++seq->tail;
seq->tail%=SeqQueueMax;
++seq->size;
}

//顺序队列的出队
int SeqQueuePop(SeqQueue* seq,SeqQueueType* value){
if(seq == NULL){
return 0;
}
if(seq->size == 0){
return 0;
}
*value = seq->data[seq->head++];
--seq->size;
seq->head %= SeqQueueMax;
return 1;
}

//取顺序队列的队首元素
int GetSeqQueueTop(SeqQueue* seq,SeqQueueType* value){
if(seq == NULL){
return 0;
}
if(seq->size == 0){
return 0;
}
*value = seq->data[seq->head];
return 1;
}
//打印顺序队列的元素,方便检测队列的基本操作
void printQueue(SeqQueue* seq,char* str){
printf("\n********%s*******\n",str);
if(seq == NULL){
return;
}
size_t i=0;
for(;isize;i++){
printf("%c ",seq->data[i]);
}
printf("\n");
}
检测代码:

//检测顺序队列的操作
void test(){
SeqQueue seq;
SeqQueueType value;
int ret;
SeqQueueInit(&seq);
SeqQueuePush(&seq,'a');
SeqQueuePush(&seq,'b');
SeqQueuePush(&seq,'c');
SeqQueuePush(&seq,'d');
printQueue(&seq,"4 Push");

//取队首元素
ret = GetSeqQueueTop(&seq,&value);
printQueue(&seq,"GetQueueTop");
printf("expect ret: 1   actual: %d\n",ret);
printf("expect value: a   actual: %c\n",value);
//第一次出队
ret = SeqQueuePop(&seq,&value);
printQueue(&seq,"1 Pop");
printf("expect ret: 1   actual: %d\n",ret);
printf("expect value: a   actual: %c\n",value);
//第二次出队
ret = SeqQueuePop(&seq,&value);
printQueue(&seq,"2 Pop");
printf("expect ret: 1   actual: %d\n",ret);
printf("expect value: b   actual: %c\n",value);
//第三次出队
ret = SeqQueuePop(&seq,&value);
printQueue(&seq,"3 Pop");
printf("expect ret: 1   actual: %d\n",ret);
printf("expect value: c   actual: %c\n",value);
//第四次出队
ret = SeqQueuePop(&seq,&value);
printQueue(&seq,"4 Pop");
printf("expect ret: 1   actual: %d\n",ret);
printf("expect value: d   actual: %c\n",value);
//对空队列进行出堆操作
ret = SeqQueuePop(&seq,&value);
printQueue(&seq,"5 Pop");
printf("expect ret: 0   actual: %d\n",ret);
//对空队列进行取队首元素
ret = GetSeqQueueTop(&seq,&value);
printQueue(&seq,"NULl GetQueueTop");
printf("expect ret: 0   actual: %d\n",ret);
}

//主函数
int main(){
test();
}

检测结果:

[chaiyandong@localhost shujujiegou]$ ./seq


********4 Push*******
a b c d 


********GetQueueTop*******
a b c d 
expect ret: 1   actual: 1
expect value: a   actual: a


********1 Pop*******
a b c 
expect ret: 1   actual: 1
expect value: a   actual: a


********2 Pop*******
a b 
expect ret: 1   actual: 1
expect value: b   actual: b


********3 Pop*******

expect ret: 1   actual: 1
expect value: c   actual: c


********4 Pop*******


expect ret: 1   actual: 1
expect value: d   actual: d


********5 Pop*******


expect ret: 0   actual: 0


********NULl GetQueueTop*******


expect ret: 0   actual: 0

你可能感兴趣的:(数据结构)