数据结构-----栈数组实现

来源:互联网 发布:整理通讯录的软件 编辑:程序博客网 时间:2024/05/18 01:32

//测试main.cpp

#include <stdio.h>#include <stdlib.h>#include "StackArray.h"int main(){  Stack S;  initStack(S);  Push(2,S);  printf("%d ",Top(S));  Push(3,S);  printf("%d ",Top(S));  Pop(S);  printf("%d",Top(S));  return 0;}


//具体实现代码StackArray.h

#ifndef STACKARRAY_H_INCLUDED#define STACKARRAY_H_INCLUDED#define LIST_INIT_SIZE 50 // 线性表存储空间的初始分配量#define LISTINCREMENT 16 // 线性表存储空间的分配增量#define EmptyTOS -1typedef int ElemType;struct StackArray{    ElemType *elem; // 存储空间基址    int Capacity; // 当前长度    int TopOfStack; // 当前分配的存储容量(以sizeof(ElemType)为单位)};typedef StackArray *Stack;int initStack(Stack &S){    S = (Stack)malloc(sizeof(struct StackArray));    S->elem = (ElemType*)malloc(sizeof(ElemType)*LIST_INIT_SIZE);    S->Capacity = LIST_INIT_SIZE;    S->TopOfStack = EmptyTOS;    return 1;}void DestoryStack(Stack S){    if(S != NULL)    {        free(S->elem);        free(S);    }}int IsEmpty(Stack S){    return S->TopOfStack == EmptyTOS;}int IsFull(Stack S){    return (S->TopOfStack > S->Capacity-1)?1:0;}void MakeEmpty(Stack S){    S->TopOfStack = EmptyTOS;}void Push(ElemType x,Stack S){    if(IsFull(S))    {       ElemType *et=(ElemType*)realloc(S->elem,sizeof(ElemType)*LISTINCREMENT);       S->elem = et;       S->Capacity += LISTINCREMENT;    }    S->elem[++S->TopOfStack]  = x;}ElemType Top(Stack S){    if(!IsEmpty(S))    {        return S->elem[S->TopOfStack];    }    return -1;}void Pop(Stack S){    if(!IsEmpty(S))    {       S->TopOfStack--;    }}#endif // STACKARRAY_H_INCLUDED


 

 

0 0
原创粉丝点击