如题;这是一套完整的可运行的代码;需要读者有一定的基础去阅读;
语言是用C语言实现;在C++环境中编写;在C++中可直接运行;在C语言中需要改部分头文件和输出语句;
头文件;这要是代码的声明部分;
# ifndef _HEAD_
# define _HEAD_
# include <iostream>
using namespace std;
typedef int DataType;
# define MAXSIZE 256
typedef struct
{
DataType data[MAXSIZE];
int top;
}SeqStack, * PSeqStack;
PSeqStack InitSeqStack(void);
void DestroySeqStack(PSeqStack * pS);
bool EmptySeqStack(PSeqStack S);
bool FullSeqStack(PSeqStack S);
bool PushSeqStack(PSeqStack S, DataType x);
bool PopSeqStack(PSeqStack S, DataType * val);
bool GetTopSeqStack(PSeqStack S, DataType * val);
# endif
实现文件;主要是代码的实现;
# include "Head.h"
PSeqStack InitSeqStack(void)
{
PSeqStack S = (PSeqStack)malloc(sizeof(SeqStack));
if (NULL != S)
{
S->top = -1;
return S;
}
else
{
cout << "Memory allocate is error! " << endl;
system("pause");
exit(0);
}
}
void DestroySeqStack(PSeqStack * pS)
{
PSeqStack S = *pS;
if (NULL != S)
{
free(S);
S = NULL;
}
*pS = NULL;
return;
}
bool EmptySeqStack(PSeqStack S)
{
if (-1 == S->top)
{
return true;
}
else
{
return false;
}
}
bool FullSeqStack(PSeqStack S)
{
if (S->top == MAXSIZE - 1)
{
return true;
}
else
{
return false;
}
}
bool PushSeqStack(PSeqStack S, DataType x)
{
if (FullSeqStack(S))
{
return false;
}
else
{
S->top++;
S->data[S->top] = x;
return true;
}
}
bool PopSeqStack(PSeqStack S, DataType * val)
{
if (EmptySeqStack(S))
{
return false;
}
else
{
*val = S->data[S->top];
S->top--;
return true;
}
}
bool GetTopSeqStack(PSeqStack S, DataType * val)
{
if (EmptySeqStack(S))
{
return false;
}
else
{
*val = S->data[S->top];
return true;
}
}
Main函数;
# include "Head.h"
int main(int argc, char ** argv)
{
int val = 0;
PSeqStack S = InitSeqStack();
for (int i = 0; i < 10; i++)
{
PushSeqStack(S, i + 1);
}
for (int i = 0; i < 10; i++)
{
PopSeqStack(S, &val);
cout << val << " ";
}
system("pause");
return 0;
}