堆栈的动态数组实现

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define n 100

typedef struct node
{
	int a[n];
	int top;
}stack;

stack *create_stack()
{
	stack *s = (stack*)malloc(sizeof(struct node));
	if (s == NULL)
		return NULL;
	else
	{
		s->top = 0; return s;
	}
}

int empty_stack(stack *s)
{
	if (s->top == 0) return 0;
	else return 1;
}

int full_stack(stack *s)
{
	if (s->top == n) return 0;
	else return 1;
}

int push(stack *s, int m)
{
	if (!full_stack(s)) return 0;
	else{
		s->a[(s->top)++] = m;
		return 1;
	}
}

int pop(stack *s)
{
	if (!empty_stack(s))  return 0;
	else{
		return (s->a[s->top--]);
	}
}

void print_stack(stack *s)
{
	int top = s->top;
	while (top)
		printf("%d ", s->a[--top]);
}

int main()
{
	int b[10] = { 55, 66, 9, 7, 4, 2, 0,10,3 };
	stack *s = create_stack();
	for (int i = 0; i < 10; i++)
		push(s, b[i]);
	pop(s);
	print_stack(s);

}

猜你喜欢

转载自blog.csdn.net/youtiankeng/article/details/87719135