栈的顺序存储结构(c语言实现)

#include 

#define MAXSIZE 20
#define T 1
#define F 0

typedef int Status;
typedef int ElemType;

typedef struct 
{
	ElemType data[MAXSIZE];
	int top;
}SqStack;

void init(SqStack* S);
Status push(SqStack* S, ElemType e);
Status pop(SqStack* S, ElemType* e);

int main()
{
	int i = 0;
	int num = 0;
	SqStack S;
	init(&S);
	for (; i < 10; i++)
	{
		push(&S, i);
	}
	for (; i > 0; i--)
	{
		pop(&S, &num);
		printf("%d\n", num);
	}
	return 0;
}

void init(SqStack* S)
{
	S->top = -1;
}

Status push(SqStack* S, ElemType e)
{
	if (S->top == MAXSIZE - 1)//栈满
	{
		return F;
	}
	S->top++;
	S->data[S->top] = e;
	return T;
}

Status pop(SqStack* S, ElemType* e)
{
	if (-1 == S->top)
	{
		return F;
	}
	*e = S->data[S->top];
	S->top--;
	return T;
}

运行结果:

栈的顺序存储结构(c语言实现)_第1张图片

简便表示方法:

#include 

#define T 1
#define F 0
#define MAX 10

typedef struct 
{
	int buf[MAX];
	int *top;
	int count;
}Stack;

int init(Stack *s);
int push(Stack *s, int e);
int pop(Stack *s, int *e);

int main()
{
	int i, e;
	Stack s;
	init(&s);
	for (i = 0; i < 5; i++)
	{
		push(&s, i);
		pop(&s, &e);
		printf("%d\n", e);
	}
	return 0;
}

int init(Stack *s)
{
	s->top = s->buf - 1;
	s->count = 0;
	return T;
}

int push(Stack *s, int e)
{
	if (MAX == s->count)
	{
		return F;
	}
	s->top ++;
	*(s->top) = e;
	s->count ++;
	return T;
}

int pop(Stack *s, int *e)
{
	if (0 == s->count)
	{
		return F;
	}
	*e = *(s->top);
	s->top --;
	s->count --;
	return T;
}

运行结果:

栈的顺序存储结构(c语言实现)_第2张图片

你可能感兴趣的:(数据结构)