c语言实现栈

栈是实现管理内存的一种方式,其特点是先进后出,一般用于存储程序的临时变量,全局变量等数据。

#include<stdio.h>
#include<string.h>
#include<malloc.h>
//定义栈,入栈,出栈,遍历栈

typedef struct 
{
    int data[100];
    int top;
    int bottom;
}stack;

//定义一个栈;
stack *stackcreate()
{
    stack* p = (stack *)malloc(sizeof(stack));
    if (p == NULL) return NULL;
    p->top = p->bottom = 0;
    return p;
}


//插入数据;
void stack_insert(int data1,stack* p)
{
    if (p->top >= 100)
    {
        printf("stack is full");
        return;
    }
    p->data[p->top] = data1;
    p->top++;    
}


//出栈数据;
int  stack_push(stack* p)
{
    int result;
    if (p->top )
    {
        
        result=p->data[p->top];
        p->top--;
        return result;
    }
    else
    {
        printf("stack is empty");
        return NULL;
    }

}


//遍历栈的数据;
void stack_scan(stack* p)
{
    int i;
    for (i=0;i<p->top;i++)
    {
        printf("%d ", p->data[i]);
    }
}



int main()
{
    stack* p = stackcreate();
    int i;
    for(i=0;i<10;i++)
    stack_insert(i, p);
    stack_scan(p);

    

    
}

 

posted @ 2019-11-14 22:45  fjc0000  阅读(143)  评论(0编辑  收藏  举报