欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-05 14:49:44
...
#include <stdio.h>

#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语言实现)

简便表示方法:

#include <stdio.h>

#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语言实现)

相关标签: 数据结构