栈的数组实现

tonymong106 2007-04-26 10:07:32
#include <stdio.h>
#include <stdlib.h>

struct StackRecord;
typedef struct StackRecord *Stack;


int IsEmpty(Stack S);
int IsFull(Stack S);
Stack CreateStack(int MaxElement);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(int X,Stack S);
void Pop(Stack S);
void Top(Stack S);

#define EmptyTOS (-1)
#define MinStackSize (5)

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


void main()
{
Stack s;
s=CreateStack(5);
Push(4,s);
Top(s);
}


Stack
CreateStack(int MaxElement)
{
Stack S;

if(MaxElement<MinStackSize)
printf("Stack is too small.");
else
S->Array=(struct StackRecord *)malloc(sizeof(Stack)*MaxElement);
if(S->Array==NULL)
printf("Out of space.");
S->Capacity=MaxElement;
MakeEmpty(S);

return S;
}


void
DisposeStack(Stack S)
{
if(S!=NULL)
{
free(S->Array);
free(S);
}
}


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


void
Push(int X,Stack S)
{
if(IsFull(S))
printf("Full Stack.");
else
S->Array[++S->TopOfStack]=X;
}


void
Pop(Stack S)
{
if(IsEmpty(S))
printf("Empty Stack.");
else
S->TopOfStack--;
}



void
Top(Stack S)
{
if(!IsEmpty(S))
printf("%d",S->Array[S->TopOfStack]);
else
printf("Empty Stack.");
}
...全文
279 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
xlfddlfd 2007-04-26
  • 打赏
  • 举报
回复
我来给楼主接分洗尘!!!
Jack_xiao 2007-04-26
  • 打赏
  • 举报
回复
顶!
COBELL 2007-04-26
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;

template<class T>
class Stack
{
public:
Stack(int = 100);
~Stack( );
void push(T x);
T pop( );
bool IsFull( );
bool IsEmpty( );
void output(ostream & );
private:
T *data;
int MaxSize;
int top;
};

template <class T>
Stack< T >::Stack(int size)
{
MaxSize = size;
data = new T[MaxSize];
top = -1;
}

template <class T>
Stack< T >::~Stack( )
{
delete data;
}

template<class T >
void Stack< T >::push(T x)
{
if(IsFull( ))
{
cerr<<"The Stack is Full\n";
exit(1);
}
data[++top] = x;
}

template< class T>
T Stack< T >::pop( )
{
if(IsEmpty( ))
{
cerr<<"The Stack is Empty\n";
exit(1);
}
return data[top--];
}

template< class T>
bool Stack< T >::IsEmpty( )
{
return top == -1;
}

template<class T>
bool Stack< T >::IsFull( )
{
return top == MaxSize - 1;
}

template<class T>
void Stack< T >::output(ostream & out)
{
for(int i=0;i<top+1;i++)
{
out<<data[i]<<' ';
if((i+1)%4==0)
cout<<endl;
}
out<<endl;
}
shunan 2007-04-26
  • 打赏
  • 举报
回复
怎么没人jf

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧