数据结构简单队列学习(c语言)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5341aa4ef0b85521621d90997a662116.png)
- 效果说明
创建并加入元素后
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/82d17c0899417dc6e78fa50ec6d48e7f.png)
删除元素后
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7dba7aa78c6e367fccb4e6b14f9efcc5.png)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef struct
{
long unsigned head;
long unsigned tail;
int *queue;
size_t arr_len;
size_t que_len;
} Queue;
void NewCommonQueue(Queue *q, size_t QueueLen);
void addElement(Queue *q, int elem);
int popElement(Queue *q);
void showQueue(Queue *q);
int main(void)
{
Queue q;
NewCommonQueue(&q, 5);
addElement(&q, 2);
addElement(&q, 3);
addElement(&q, 4);
addElement(&q, 5);
addElement(&q, 6);
showQueue(&q);
puts("");
int A = popElement(&q);
int B = popElement(&q);
showQueue(&q);
puts("");
printf("A = %d\n", A);
printf("B = %d\n", B);
free(q.queue);
return 0;
}
int popElement(Queue *q)
{
if(q == NULL)
{
fputs("NULL point exception\n", stderr);
exit(0);
}
if(q->head == q->tail)
{
fputs("Queue empty\n", stderr);
exit(0);
}
int ret = q->queue[q->head + 1];
q->head += 1;
q->que_len = q->tail - q->head;
return ret;
}
void showQueue(Queue *q)
{
printf("head = %lu\n", q->head);
printf("tail = %lu\n", q->tail);
int *arr = &q->queue[q->head] + 1;
size_t i;
printf("{ ");
for(i = 0; i < q->que_len; i++)
{
printf("%d ", arr[i]);
}
printf("}");
puts("");
return;
}
void addElement(Queue *q, int elem)
{
if(q == NULL)
{
fputs("Null point exception\n", stderr);
exit(0);
}
q->tail += 1;
if(q->tail > q->arr_len - 1)
{
fputs("Queue tail err!\n", stderr);
exit(0);
}
q->queue[q->tail] = elem;
q->que_len = q->tail - q->head;
return;
}
void NewCommonQueue(Queue *q, size_t QueueLen)
{
if(q == NULL)
{
fputs("Null point exception\n", stderr);
exit(0);
}
int *newArray = (int *)malloc(sizeof(int) * (QueueLen + 1));
if(newArray == NULL)
{
fputs("malloc error!!!\n", stderr);
exit(0);
}
q->arr_len = QueueLen + 1;
q->head = 0;
q->tail = 0;
q->queue = newArray;
q->que_len = q->tail - q->head;
return;
}