(数据结构)队列

队列,一种线性存储结构。

特点:1.队列中的数据是按照“先进先出”的方式进出队列的。

2.队列只允许在“队首”进行删除操作,在“队尾”进行插入操作。

队列通常包括两种操作:入队列出队列

C语言实现:数组实现的队列,并且只能存储int数据

#include <stdio.h>
#include <malloc.h>

/**
 * C 语言: 数组实现的队列,只能存储int数据。
 *
 * @author skywang
 * @date 2013/11/07
 */

// 保存数据的数组
static int *arr=NULL;
// 队列的实际大小
static int count;

// 创建“队列”
int create_array_queue(int sz) 
{
    arr = (int *)malloc(sz*sizeof(int));
    if (!arr) 
    {
        printf("arr malloc error!");
        return -1;
    }
    count = 0;

    return 0;
}

// 销毁“队列”
int destroy_array_queue() 
{
    if (arr) 
    {
        free(arr);
        arr = NULL;
    }

    return 0;
}

// 将val添加到队列的末尾
void add(int val) 
{
    arr[count++] = val;
}

// 返回“队列开头元素”
int front() 
{
    return arr[0];
}

// 返回并删除“队列开头元素”
int pop() 
{
    int i = 0;;
    int ret = arr[0];

    count--;
    while (i++<count)
        arr[i-1] = arr[i];

    return ret;
}

// 返回“队列”的大小
int size() 
{
    return count;
}

// 返回“队列”是否为空
int is_empty()
{
    return count==0;
}

void main() 
{
    int tmp=0;

    // 创建“队列”
    create_array_queue(12);

    // 将10, 20, 30 依次推入队列中
    add(10);
    add(20);
    add(30);

    // 将“队列开头的元素”赋值给tmp,并删除“该元素”
    tmp = pop();
    printf("tmp=%d\n", tmp);

    // 只将“队列开头的元素”赋值给tmp,不删除该元素.
    tmp = front();
    printf("tmp=%d\n", tmp);

    add(40);

    // 打印队列
    printf("is_empty()=%d\n", is_empty());
    printf("size()=%d\n", size());
    while (!is_empty())
    {
        printf("%d\n", pop());
    }

    // 销毁队列
    destroy_array_queue();
}

运行结果

tmp=10
tmp=20
is_empty()=0
size()=3
30

解释:在main函数中,先将“10.20.30”一次入队列,队列的数据是:10-->20-->30

下一步,通过pop()返回队首元素,pop()操作并不会改变数列中的数据:10-->20-->30

下一步,通过front()返回并删除队首元素,,队列中的数据:20-->30

最后,通过add(40)将40入队列,队列中的数据:20-->30-->40

猜你喜欢

转载自blog.csdn.net/niuyuce/article/details/84954470