栈-顺序结构C++实现:
//顺序栈头文件SequenceStack.h
//@ggzhoulei
//@2010-12-20
#ifndef _SEQUENCESTACK_H_
#define _SEQUENCESTACK_H_
#include <iostream>
using namespace std;
//栈的最大元素个数为(MaxStackSize - 1): S[1...(MaxStackSize - 1)]
#define MaxStackSize 4
//数据类型定义
typedef struct DataT
{
char stuno[10];
}DataType;
//栈类定义
class SeqStack
{
private:
DataType data[MaxStackSize];
int top;
public:
//构造函数
SeqStack();
//析构函数
~SeqStack();
//栈中元素的个数
int Length();
//是否空栈
bool IsEmpty();
//进栈
void Push(DataType);
//出栈
DataType Pop();
//获得栈顶元素
DataType GetTop();
//遍历栈元素
void Traverse();
};
#endif
//顺序栈头文件实现SequenceSeqStack.cpp
#include "SequenceStack.h"
//构造函数
SeqStack::SeqStack()
{
//栈为空
top = 0;
}
//析构函数
SeqStack::~SeqStack()
{
}
//栈中元素的个数
int SeqStack::Length()
{
return top;
}
//是否空栈
bool SeqStack::IsEmpty()
{
return top == 0;
}
//进栈
void SeqStack::Push(DataType x)
{
if(top >= MaxStackSize - 1)
{
cerr<<"Push failed:SeqStack is full."<<endl;
exit(1);
}
else
{
top ++;
data[top] = x;
}
}
//出栈
DataType SeqStack::Pop()
{
if(IsEmpty())
{
cerr<<"Pop failed:SeqStack is empty."<<endl;
exit(1);
}
else
{
top --;
return data[top + 1];
}
}
//获得栈顶元素
DataType SeqStack::GetTop()
{
return data[top];
}
//遍历栈元素
void SeqStack::Traverse()
{
int i = top;
while(i > 0)
{
cout<<data[i].stuno<<endl;
i --;
}
}
测试代码:
//测试代码 SequenceStackTest.cpp
#include <iostream>
#include <cstring>
#include "SequenceStack.h"
using namespace std;
void main()
{
SeqStack s1;
DataType t1,t2,t3,t4,tmp;
strcpy(t1.stuno,"10001");
strcpy(t2.stuno,"10002");
strcpy(t3.stuno,"10003");
strcpy(t4.stuno,"10004");
cout<<"Empty?"<<s1.IsEmpty()<<endl;
s1.Push(t1);
s1.Push(t2);
s1.Push(t3);
//Test when stack is full
//s1.Push(t4);
cout<<"SeqStack Traverse:"<<endl;
s1.Traverse();
cout<<"Empty?"<<s1.IsEmpty()<<endl;
cout<<"length="<<s1.Length()<<endl;
cout<<"Get top:"<<s1.GetTop().stuno<<endl;
tmp = s1.Pop();
cout<<"After Pop "<<tmp.stuno<<":"<<endl;
s1.Traverse();
cout<<"Get top:"<<s1.GetTop().stuno<<endl;
tmp = s1.Pop();
cout<<"After Pop "<<tmp.stuno<<":"<<endl;
s1.Traverse();
cout<<"Get top:"<<s1.GetTop().stuno<<endl;
tmp = s1.Pop();
cout<<"After Pop "<<tmp.stuno<<":"<<endl;
s1.Traverse();
//Test when stack is empty
//tmp = s1.Pop();
}
测试结果:
Empty?1
SeqStack Traverse:
10003
10002
10001
Empty?0
length=3
Get top:10003
After Pop 10003:
10002
10001
Get top:10002
After Pop 10002:
10001
Get top:10001
After Pop 10001:
请按任意键继续. . .