栈的实现(C语言)

栈的原理:
先进后出原则!!!

1、限定仅在表尾进行插入或删除操作的线性表

2、栈顶:表尾端 

3、栈底:表头端

4、应用:数制转换,行编辑程序,树的遍历等

5、凡是对数据的处理具有“后进先出(LIFO)”的特点,都可以用栈这种数据结构来操作

栈的实现(C语言)_第1张图片


demo:用链表实现栈!

#include 
#include 
#include 

struct Link
{
    int data;
    struct Link* next;
};

struct Stack
{
    struct Link* head;
    int size;
};

void StackInit(struct Stack* stack)
{
    stack->head = NULL;
    stack->size = 0;
}

void StackPush(struct Stack* stack, const int data)//进栈
{
    struct Link* node;
    node = (struct Link*)malloc(sizeof(struct Link));
    assert(node != NULL);
    node->data = data;
    node->next = stack->head;
    stack->head = node;
    ++stack->size;
}

int StackEmpty(struct Stack* stack)
{
    return (stack->size == 0);
}

int StackPop(struct Stack* stack, int* data)//出栈
{
    if (StackEmpty(stack))
    {
        return 0;
    }

    struct Link* tmp = stack->head;
    *data = stack->head->data;
    stack->head = stack->head->next;
    free(tmp);
    --stack->size;

    return 1;
}

void StackCleanup(struct Stack* stack)
{
    struct Link* tmp;
    while (stack->head)
    {
        tmp = stack->head;
        stack->head = stack->head->next;
        free(tmp);
    }

    stack->size = 0;
}

int main(void)
{
    struct Stack stack;
    StackInit(&stack);
    int i;
    for (i=0; i<5; i++)
    {
        StackPush(&stack, i);
    }

    while (!StackEmpty(&stack))
    {
        StackPop(&stack, &i);
        printf("%d ", i);
    }
    printf("\n");

    return 0;
}

你可能感兴趣的:(C语言)