码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构 栈笔记

时间:2017-04-16 13:29:07      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:blog   new   头部   动态内存   val   clu   data   个数   creat   

// 数据结构 栈的实现 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 = 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;
}

 

数据结构 栈笔记

标签:blog   new   头部   动态内存   val   clu   data   个数   creat   

原文地址:http://www.cnblogs.com/lnlin/p/6718341.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!