C实现数据结构

// 队列的C语言数组实现
#define QUEUE_MAX_LEN 10
int main()
{
    int head = 0, tail = 0; // 队首、队尾标志变量
    int queue[QUEUE_MAX_LEN] = { 0 }; // 模拟队列

    queue[tail++] = 0; // 入队操作
    while (head != tail) { // 队列判空操作
        int front = queue[head]; // 取队首元素操作
        head++; // 出队操作
    }

    return 0;
}

// 循环队列的C语言数组实现,使用时需能够预估队列的大小并提前分配数组空间,新数据覆盖旧数据
#define QUEUE_MAX_LEN 10
int main()
{
    int head = 0, tail = 0; // 队首、队尾标志变量
    int queue[QUEUE_MAX_LEN] = { 0 }; // 模拟队列

    tail = (tail + 1) % QUEUE_MAX_LEN; // 移动队尾标志变量
    queue[tail] = 0; // 入队操作
    while (head != tail) { // 队列判空操作
        int front = queue[head]; // 取队首元素操作
        head = (head + 1) % QUEUE_MAX_LEN; // 出队操作
    }

    return 0;
}
// 栈的C语言数组实现,需要能够预估栈大小,提前分配数组空间
#define STACK_MAX_LEN 10
int main()
{
    int top = 0; // 栈顶指针
    int stack[STACK_MAX_LEN] = { 0 }; // 模拟栈

    stack[++top] = 0; // 入栈操作,0号位作为栈空标志位,不存储数据
    while (top != 0) { // 栈判空操作
        int value = stack[top--]; // 出栈操作
    }

    return 0;
}

// 完全二叉树的C语言数组实现
#define TREE_MAX_LEN 10
int main()
{
    int tree[TREE_MAX_LEN] = { 0 }; // 二叉树的数组空间
    int index = 0; // 数组索引
    tree[2*index+1] = 1; // 左子节点
    tree[2*index+2] = 2; // 右子节点
    if (index > 0) {
        tree[(index - 1) / 2] = 3; // 父节点,注意二叉树的根节点没有父节点
    }

    return 0;
}

// 堆的C语言数组实现

#define HEAP_MAX_LEN 10
int main()
{
    int array[5] = { 3, 1, 5, 4, 2 };
    int heap_size = 0; // heap元素个数
    int heap[HEAP_MAX_LEN] = { 0 };

    // 入堆操作
    for (int i = 0; i < 5; i++) {
        int index = heap_size++;
        while (index > 0) {
            //if (array[i] < heap[(index-1)/2]) { // 大堆
            if (array[i] > heap[(index-1)/2]) { // 小堆
                break;
            }
            heap[index] = heap[(index-1)/2];
            index = (index - 1) / 2;
        }
        heap[index] = array[i];
    }

    // 出堆操作
    while (heap_size > 0) {
        printf("%d ", heap[0]);
        heap_size--;
        int index = 0;
        while (index * 2 + 1 < heap_size) {
            //int cur = heap[index * 2 + 1] > heap[index * 2 + 2] ? index * 2 + 1 : index * 2 + 2; // 大堆
            int cur = heap[index * 2 + 1] < heap[index * 2 + 2] ? index * 2 + 1 : index * 2 + 2; // 小堆
            heap[index] = heap[cur];
            index = cur;
        }
        heap[index] = heap[heap_size];
    }

    return 0;
}

 

posted @ 2020-08-17 23:56  斜风戏雨  阅读(193)  评论(0)    收藏  举报