首页 > 代码库 > 数据结构 栈笔记

数据结构 栈笔记

// 数据结构 栈的实现 C语言, 只能从头部储存和销毁数据

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


// 线性储存部分
typedef struct NONE
{
    int data;
    struct NONE * pNext;
}None, * pNone;


// 栈的头部和底部
typedef struct stack
{
    pNone top;
    pNone bottom;
}St, * pSt;

// 创建一个空栈
void Create_Stack(pSt stack);
// 压栈
void Push_Stack(pSt stack, int val);
// 出栈, 返回出栈的那个节点的数据
int Out_Stack(pSt stack);
// 计算栈中数据个数
int Compute_Stack(pSt stack);
// 栈的遍历
void Travel_Stack(pSt stack); 

int main(void)
{
    St stack;
    Create_Stack(&stack);
    Push_Stack(&stack, 1);
    Push_Stack(&stack, 1);
    Push_Stack(&stack, 1);
    Push_Stack(&stack, 1);
    int cnt = Compute_Stack(&stack);
    printf("此时栈中共有%d个元素!\n", cnt);
    Out_Stack(&stack);
    cnt = Compute_Stack(&stack);
    printf("此时栈中共有%d个元素!\n", cnt);
    Travel_Stack(&stack);
    
    return 0;
}

void Create_Stack(pSt stack)
{
    stack->top = (pNone)malloc(sizeof(None));
    if (NULL == stack->top)
    {
        printf("动态内存分配失败!\n");
        exit(-1);
    }
    else
    {
        stack->bottom = stack->top;
        stack->top->pNext = NULL;
    }

    return;
}

void Push_Stack(pSt stack, int val)
{
    pNone pNew = (pNone)malloc(sizeof(None));
    if (NULL == pNew)
    {
        printf("动态内存分配失败!\n");
        exit(-1);
    }
    pNew->data =http://www.mamicode.com/ val;
    pNew->pNext = stack->top;
    stack->top = pNew;

    return;
}

int Out_Stack(pSt stack)
{
    int val;
    pNone pOut;
    pOut = stack->top;
    val = pOut->data;
    stack->top = pOut->pNext;

    return val;
}

int Compute_Stack(pSt stack)
{
    int cnt = 0;  // 记录元素个数
    pNone pTemp = stack->top;
    while (pTemp != stack->bottom)
    {
        ++cnt;
        pTemp = pTemp->pNext;
    }

    return cnt;
}

void Travel_Stack(pSt stack)
{
    pNone pTemp = stack->top;
    while (pTemp != stack->bottom)
    {
        printf("%d\n", pTemp->data);
        pTemp = pTemp->pNext;
    }
    
    return;
}

 

数据结构 栈笔记