如題;這是一套完整的可運行的代碼;需要讀者有一定的基礎去閱讀;
語言是用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;
}