C语言 简单的栈操作

这里分享一下简单的静态栈的操作。代码简单,就不作注释和解释了

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

#define N 5

struct Node
{
    int *base;
    int *top;
    int size;
} node;

void print()
{
    int *p;
    p = node.top;
    while(p-node.base > 0)  //top刚开始是N,所以要大于0 
    {
        p--;
        printf("%d  ",*p);
    }
    putchar('\n');
}

void init()
{
    node.size = N;
    node.base = (int*)malloc(sizeof(int));
    node.top = node.base;
    printf("node.base = %d, node.top = %d\n",node.base,node.top);

    puts("Init!----");
    int i=0;
    while(node.top < node.base+node.size)
    {
        *node.top = i++;
        node.top++;
    }

    puts("After Init----");
    print();
}

void mypush(int temp)
{
    if(node.top-node.base >= node.size)
        printf("\nPush failed, the stack is full!\n");
    else
    {
        printf("\nPush success, the push number is %d\n",temp);
        *node.top = temp;
        node.top++;

        puts("\nAfter push----");
        print();
    }   
}

int* mypop()
{

    if(node.top == node.base)
    {
        puts("\nPop failed, the stack is empty!");
        return NULL;
    }
    else
    {
        node.top--;
        printf("The pop number is %d\n",*node.top);

        puts("\nAfter pop----");
        print();

        return node.top;
    }
}


int main()
{
    int* p;

    init();
    mypush(100);
    p = mypop();

    if(p != NULL)
        printf("p = %d\n",*p);

    mypush(100);

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值