栈———数组实现

栈(stack)是一种比较基础的数据结构,其限制了删除和插入在一个位置操作,而其主要思想就是后进先出(LIFO)。

操作图示:

具体细节可通过代码看出。

下面给出函数的声明部分:

StackRecord.h

#ifndef STACKRECORD_H
#define STACKRECORD_H

typedef char ElementType;
struct StackRecord; typedef struct StackRecord *Stack; int IsEmpty(Stack S); int IsFull(Stack S); Stack CreateStack(int MaxStackSize); void DisposeStack(Stack S); void MakeEmpty(Stack S); void Push(Stack S, ElementType X); void Pop(Stack S); ElementType Top(Stack S); ElementType PopAndTop(Stack S); #endif

一般的,当我们创建一个栈时都会声明一个数组来储存元素,但是这是一个隐含的危险,一般数组大小都会有一个确定的值,而通常我们的程序往往潜在的存在多个栈。因此我们动态的申请一个数组,虽然贵这样花费了昂贵的malloc和free程序时间,但是这很符合我们ADT的想法!

栈的主要例程是Push()和Pop()两个例程:

StackFunction.c:

#include"StackRecord.h"
#include<stdio.h>
#include<stdlib.h>

#define EmptyStack -1/*默认空栈大小*/
#define MinStackSize 5

struct StackRecord{
    int Capacity;
    int TopOfStack;
    ElementType *Array;
};

int IsEmpty(Stack S)
{
    return S->TopOfStack == EmptyStack;
}

int IsFull(Stack S)
{
    return S->Capacity == S->TopOfStack + 1;/*加1因为数组的大小从0开始*/
}

Stack CreateStack(int MaxStackSize)
{
    Stack S;
    if(MaxStackSize < MinStackSize)
        printf("Stack is too small!");
    S = (Stack)malloc(sizeof(struct StackRecord));
    if(S == NULL)
        printf("malloc failure!");
    else{
/*Alloc a Arry size you wanted*/ S
->Array = (ElementType*)malloc(sizeof(ElementType) * MaxStackSize); if(S->Array == NULL) printf("malloc failure!"); else{ S->Capacity = MaxStackSize; MakeEmpty(S); } } return S; } void MakeEmpty(Stack S) { S->TopOfStack = EmptyStack; } void DisposeStack(Stack S) { if(S != NULL){//if S is NULL, that free(S) is meaningless free(S->Array); free(S); } } void Push(Stack S, ElementType X) { if(IsFull(S)) printf("Stack is full!"); else S->Array[++S->TopOfStack] = X; } void Pop(Stack S) { if(IsEmpty(S)) printf("Stack is empty!"); else S->TopOfStack--; } ElementType Top(Stack S) { if(!IsEmpty(S)) return S->Array[S->TopOfStack]; printf("Stack is empty!"); return 0;//return value used to avoid warning } ElementType PopAndTop(Stack S) { if(!IsEmpty(S)) return S->Array[S->TopOfStack--]; printf("Stack is empty!"); return 0; }

转载于:https://www.cnblogs.com/Crel-Devi/p/9460945.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值