顺序栈
#include <iostream>
using namespace std;
#define MaxSize 100
template<typename ElemType>
struct SqStack {
ElemType* base;
ElemType* top;
};
template<typename ElemType> bool initSqStack(SqStack<ElemType>& sq)
{
sq.base = new ElemType[MaxSize];
if (!sq.base)
{
return false;
}
sq.top = sq.base;
return true;
}
template<typename ElemType> bool pushSqStack(SqStack<ElemType>& sq, ElemType data)
{
if (sq.top - sq.base >= MaxSize)
return false;
*(sq.top)++ = data;
return true;
}
template<typename ElemType> bool popSqStack(SqStack<ElemType>& sq, ElemType& data)
{
if (sq.top == sq.base)
return false;
data = *(--sq.top);
return true;
}
链栈
template<typename ElemType>
struct LinkNode {
ElemType data;
struct LinkNode* next;
};
template<typename ElemType> LinkNode<ElemType>* initLinkStack()
{
LinkNode<ElemType>* s = new LinkNode<ElemType>;
if (!s)
return NULL;
s->next = NULL;
return s;
}
template<typename ElemType> bool pushLinkStack(LinkNode<ElemType>** s, ElemType data)
{
LinkNode<ElemType>* tmp = new LinkNode<ElemType>;
if (!tmp)
{
return false;
}
tmp->next = *s;
*s = tmp;
(*s)->data = data;
return true;
}
template<typename ElemType> bool popLinkStack(LinkNode<ElemType>** s, ElemType& data)
{
if (!(*s)->next)
return false;
data = (*s)->data;
LinkNode<ElemType>* tmp = (*s)->next;
delete (*s);
*s = tmp;
return true;
}
测试
int main()
{
SqStack<int> sq;
LinkNode<int>* s = initLinkStack<int>();
int data;
initSqStack(sq);
for (int i = 0; i < 10; i++)
pushSqStack(sq, i);
cout << "顺序栈:" << endl;
while (popSqStack(sq, data))
cout << "data = " << data << endl;
for (int i = 0; i < 10; i++)
pushLinkStack(&s, i);
cout << "链栈:" << endl;
while (popLinkStack(&s, data))
cout << "data = " << data << endl;
getchar();
return 0;
}