码迷,mamicode.com
首页 > 编程语言 > 详细

C语言实现栈

时间:2015-10-26 22:35:45      阅读:243      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct stack_tag{
    int top;
    int num;
    int *data;
} stack;

stack * stack_init(int num){
    stack *s = (stack*)malloc(sizeof(stack));
    s->num = num;
    s->data = (int*)malloc(sizeof(int) * num);
    s->top = -1; 
    return s;
}

void stack_destroy(stack *s){
    free(s->data);
    free(s);
}

int stack_push(stack *s, int data){
    if(s->top == s->num - 1)
        return -1; 
    s->data[++s->top] = data;
    return 0;
}

int stack_pop(stack *s, int *data){
    if(s->top == -1){
        return -1; 
    }   
    *data =  s->data[s->top --];
    return 0;
}
bool stack_empty(stack *s){
    return s->top == -1;
}

int main() {
    stack *s = stack_init(3);
    stack_push(s, 1);
    stack_push(s, 2);
    while(!stack_empty(s)){
        int data = 0;
        stack_pop(s, &data);
        printf("%d\n", data);
    }
    return 0;
}

  

C语言实现栈

标签:

原文地址:http://www.cnblogs.com/moxiaopeng/p/4912430.html

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