顺序栈

一、栈简述

栈是一种特殊的线性表,其特殊性在于栈的基本操作是线性表操作的一个子集。栈按“先进后出”的规则进行操作,故称其为操作受限的线性表。

1、栈的定义
栈是只能在一端进行插入和删除操作的线性表。该操作端为线性表的表尾,称为栈顶(top)。栈的第一个数据元素称之为栈顶元素。栈的另一端称之为栈底(bottom)。当栈中没有数据元素时称为空栈。栈的插入操作被形象地称之为进栈或入栈(push),删除操作称为出栈或退栈(pop)。

2、栈的特点
每次进栈的元素都被放在原栈顶元素之上而称为新的栈顶元素,而每次出栈的总是最后进栈的元素。

3、图解栈

在这里插入图片描述

二、栈

#pragma once

#define STACK_INIT_SIZE 10
#define STACKINCREMENT 5

typedef int ElemType;

typedef struct Stack
{
	ElemType *base;
	int top;
	int stacksize;
}SqStack;

void InitStack(SqStack *st);

int EmptyStack(SqStack *st);

int PushStack(SqStack *st, ElemType val);

int GetTop(Stack *st, ElemType *val);

int PopStack(SqStack *st, ElemType *val);

void ClearStack(SqStack *st);

void DestoryStack(SqStack *st);
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include "stack.h"

static void DeterPointIsNULL(SqStack *st)
{
	assert(st != NULL);
	if (st == NULL)
	{
		exit(0);
	}
}

static void ExpandSpace(SqStack *st)
{
	ElemType * s = (ElemType *)malloc(sizeof(ElemType)* (st->stacksize + STACKINCREMENT));

	for (int i = 0; i < st->stacksize; ++i)
	{
		s[i] = st->base[i];
	}

	free(st->base);

	st->base = s;
	st->stacksize += STACKINCREMENT;
}

void InitStack(SqStack *st)
{
	DeterPointIsNULL(st);

	st->base = (ElemType *)malloc(sizeof(ElemType)* STACK_INIT_SIZE);
	assert(st->base != NULL);
	
	st->top = 0;
	st->stacksize = STACK_INIT_SIZE;
}

int EmptyStack(SqStack *st)
{
	DeterPointIsNULL(st);

	if (st->top == 0)
	{
		return 1;
	}

	return 0;
}

int PushStack(SqStack *st, ElemType val)
{
	DeterPointIsNULL(st);

	if (st->top == st->stacksize)
	{
		ExpandSpace(st);
	}

	st->base[st->top++] = val;

	return 1;
}

int GetTop(Stack *st, ElemType *val)
{
	DeterPointIsNULL(st);

	if (EmptyStack(st))
	{
		return 0;
	}

	*val = st->base[st->top - 1];

	return 1;
}

int PopStack(SqStack *st, ElemType *val)
{
	DeterPointIsNULL(st);

	if (!GetTop(st, val))
	{
		return 0;
	}

	st->top--;
	return 1;
}

void ClearStack(SqStack *st)
{
	DeterPointIsNULL(st);

	st->top = 0;
}

void DestoryStack(SqStack *st)
{
	DeterPointIsNULL(st);

	free(st->base);
	st->top = 0;
	st->stacksize = 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值