1. 程式人生 > >C語言實現棧(陣列)

C語言實現棧(陣列)

陣列實現棧

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 1000
#define element_type int

typedef struct 
{
    element_type data[MAXSIZE];
    int top;
}Stack;
/*初始化棧*/
Stack * init_stack()
{
    Stack * stack;
    stack = (Stack*)malloc(sizeof(element_type)*MAXSIZE);
    stack->top = -1
; return stack; } /*判斷棧是否為空*/ int is_empty(Stack *stack) { if(stack->top==-1){ printf("棧空"); return 1; } return 0; } /*是否滿棧*/ int is_full(Stack *stack) { if(stack->top==MAXSIZE-1){ printf("棧滿"); return 1; } return 0; } /*壓棧*/ void push(Stack * stack
,element_type elem) { if(!is_full(stack)){ stack->data[++stack->top] = elem; } } /*彈棧*/ element_type pop(Stack *stack) { if(is_empty(stack)){ return -1; } return stack->data[stack->top--]; } /*列印當前棧中所有元素*/ void print_stack(Stack * stack) { for(int i=stack
->top;i>=0;i--){ printf("%d ",stack->data[i]); } } int main() { Stack *stack; stack = init_stack(); push(stack,1); push(stack,2); push(stack,3); push(stack,4); push(stack,5); printf("%d ",pop(stack)); printf("%d \n",pop(stack)); print_stack(stack); return 0; }