C的指针疑惑:C和指针17(经典抽象数据类型)

堆栈这种数据最鲜明的特点是:后进先出。

用动态数组实现堆栈:

#include "C17.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>

static STACK_TYPE *stack;
//static size_t stack_size
static int stack_size;
static int top_element = -1;

void create_stack(int size)
{
    assert(stack_size == 0);
    stack_size = size;
    stack = (STACK_TYPE *)malloc(stack_size * sizeof(STACK_TYPE));
    assert(stack != NULL);
}

void destroy_stack(void)
{
    assert(stack_size > 0);
    stack_size = 0;
    free (stack);
    stack = NULL;
}

void push (STACK_TYPE value)
{
    assert(! is_full());
    top_element += 1;
    stack[top_element] = value;
}

void pop(void)
{
    assert(!is_empty());
    top_element -= 1;
}

STACK_TYPE top(void)
{
    assert(!is_empty());
    return stack[top_element];
}

int is_empty(void)
{
    assert(stack_size > 0);
    return top_element == -1;
}

int is_full(void)
{
    assert(stack_size > 0);
    return top_element == stack_size -1;
}


int main(void)
{
    int ret,i;
    create_stack(5);
    for(i= 0;i<5;i++)
    {
        push(i);
    }

    for(i= 0;i<5;i++)
    {
        ret = top();
        printf("dynamic data: %d
",ret);
        pop();
    }
}

链式堆栈:

#include "C17.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>

#define FALSE  0

typedef struct STACK_NODE
{
    STACK_TYPE   value;
    struct STACK_NODE *next;
}StackNode;

static StackNode *stack;
//static int stack_size;
//static int top_element = -1;

void create_stack(int size)
{

}

void destroy_stack(void)
{
    while(!is_empty())
        pop();
}

void push (STACK_TYPE value)
{
    StackNode *new_node;
    new_node = (StackNode *)malloc(sizeof(StackNode));
    assert(new_node != NULL);
    new_node->value = value;
    new_node->next = stack;
    stack = new_node;
}

void pop(void)
{
    StackNode *first_node;

    assert(!is_empty());
    first_node =stack;
    stack = first_node->next;
    free(first_node);
}

STACK_TYPE top(void)
{
    assert(!is_empty());
    return stack->value;
}

int is_empty(void)
{
    return stack == NULL;
}

int is_full(void)
{
    return FALSE;
}


int main(void)
{
    int ret,i;
    //create_stack(5);
    for(i= 0;i<5;i++)
    {
        push(i);
    }

    for(i= 0;i<5;i++)
    {
        ret = top();
        printf("dynamic data: %d
",ret);
        pop();
    }
}

队列:是一种先进先出的结构。需要两个指针:一个指向队头,一个指向队尾。

 

树:

属性:每个节点的值比它的左子树的所有节点的值都要大,但比它的右子树的所有节点的值都要小。

树的遍历:前序、中序、后序、层次遍历

前序遍历:检查节点的值->递归遍历左子树和右子树。

中序遍历:遍历左子树->检查当前节点的值->遍历右子树。。

后序遍历:遍历左右子树->检查当前节点的值。

层次遍历:逐层检查树的节点。处理根节点->处理它的孩子->处理它的孙子。

原文地址:https://www.cnblogs.com/Caden-liu8888/p/6607647.html