C语言实现堆栈

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

#define MAXSIZE 128
typedef int elementType;

typedef struct{
	elementType data[MAXSIZE];
	int top;
}Stack;

int InitStack(Stack **stack){
	
	*stack = (Stack*)malloc(sizeof(Stack));
	if(*stack == NULL)
		return -1;
	(*stack)->top = -1;
	
	return 0;
}

int PushStack(Stack* stack, elementType in){
	if(stack->top == MAXSIZE-1){ //栈满
		return -1;
	}
	stack->top++;
	stack->data[stack->top] = in;
	return 0;
}

int PopStack(Stack* stack, elementType* out){
	if(stack->top == -1){ //空栈 
		return -1;
	}
	*out = stack->data[stack->top];
	stack->top--;
	return 0;
}

int main(void)
{
	int i = 0, ret = 0;
	elementType out;
	Stack *stack;
	
	ret = InitStack(&stack);
	if(ret == -1) {
		printf("InitStack failed!\n");
	}
	for(; i < 10; i++) {
		PushStack(stack, i);
	}

	while(stack->top != -1) {
		PopStack(stack, &out);
		printf("%d\t", out);
	}
	
	return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页