1. 程式人生 > >棧———數組實現

棧———數組實現

int size 具體細節 思想 tac cti ise sizeof dto

棧(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; }

棧———數組實現