The establishment and operation of the order of the stack

A, as follows

/*
项目名称:顺序栈的建立与基本操作

编译环境:VC++ 2008

作者相关:。。。

最后修改:2019.6.20


学习目标:初始化、销毁、清空、判空、求长、返回栈顶元素、插入元素、删除元素、输出栈中元素

注意事项:1.测试所有功能是否正常

2.s->base = (ElemType *)realloc(s->base,
(s->stacksize + STACKINCREMENT)*sizeof(ElemType));
这是栈满追加空间



*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define STACK_INIT_SIZE 100
#define STACKINCREMENT    10
#define ERROR             0
#define OK                1

typedef int  ElemType;
typedef bool Status;

typedef struct{

	ElemType *base;//在构造之前和销毁之后base的值为NULL
	ElemType *top;
	int stacksize;//当前已分配的存储空间

}SqStack;

Status InitStack(SqStack *s);

Status DestroyStack(SqStack *s);

Status ClearStack(SqStack *s);

Status StackEmpty(SqStack s);

int StackLength(SqStack s);

Status GetTop(SqStack s,ElemType *e);

Status Push(SqStack *s,ElemType e);

Status Pop(SqStack *s,ElemType *e);

Status StackTraverse(SqStack s);

Status visit(ElemType c);

int main()
{
	SqStack s;
	ElemType e;

	if(InitStack(&s))
		printf("栈初始化成功!\n\n");

	if(StackEmpty(s))
		printf("栈为空!\n\n");
	else
		printf("栈非空!\n\n");

	srand(time(0));
	for(int i=0;i<10;i++)
	{
		e = rand()%20+1;//1~20随机
		Push(&s,e);
	}

	StackTraverse(s);

	int k = StackLength(s);
	printf("栈的长度:%d \n\n",k);

	GetTop(s,&e);
	printf("栈顶元素为:%d \n\n",e);

	Pop(&s,&e);
	printf("删除的元素为;%d \n\n",e);

	StackTraverse(s);

	ClearStack(&s);

	DestroyStack(&s);

	return 0;
}


Status InitStack(SqStack *s)
{
	s->base = (ElemType *)malloc(sizeof(STACK_INIT_SIZE*sizeof(ElemType)));//开辟内存
	if(!s->base) 
		return ERROR;

	s->top = s->base;//均为NULL
	s->stacksize = STACK_INIT_SIZE;

	return OK;
}

Status DestroyStack(SqStack *s)
{
	free(s->base);

	return OK;
}

Status ClearStack(SqStack *s)
{
	s->top = s->base = NULL;

	return OK;
}

Status StackEmpty(SqStack s)
{
	if(s.top-s.base == 0)
		return true;
	else
		return false;
}

int StackLength(SqStack s)
{
	return s.top-s.base;
}


Status GetTop(SqStack s,ElemType *e)
{
	if(!StackEmpty(s))
	{
		*e = *(s.top-1);
		return OK;
	}
	else
		return ERROR;
}

Status Push(SqStack *s,ElemType e)
{
	if(s->stacksize <= StackLength(*s))//栈满,追加空间
	{
		s->base = (ElemType *)realloc(s->base,
			(s->stacksize + STACKINCREMENT)*sizeof(ElemType));

		if(!s->base)
			return ERROR;
		s->top = s->base + s->stacksize;//top指向栈顶
		s->stacksize += STACKINCREMENT;
	}
	*s->top++ = e;

	return OK;

}

Status Pop(SqStack *s,ElemType *e)
{
	if(!StackEmpty(*s))
	{
		*e = *--s->top;
	}
	else
		return ERROR;
}

Status visit(ElemType *e)
{
	printf("%d ",*e);
	return OK;
}

Status StackTraverse(SqStack s)
{
	printf("栈中内容: ");
	while(s.base!=s.top)
	{
		visit(s.base);
		++s.base;
	}
	printf("\n\n");
	return OK;
}

Second, the results

Guess you like

Origin blog.csdn.net/Sruggle/article/details/93133744