一、实验目的
1、熟练掌栈的结构特点,掌握栈的顺序存储和链式存储结构和实现。
2、 学会使用栈解决实际问题。
二、实验内容
自己确定结点的具体数据类型和问题规模:
分别建立一个顺序栈和链栈,实现栈的压栈和出栈操作。
1、依据实验内容分别说明实验程序中用到的数据类型的定义;
2、相关操作的算法表达;
3、完整程序;
4、总结、运行结果和分析。
5、总体收获和不足,疑问等。
四、实验代码
顺序栈
#define SeqStack_H
const int StackSize=10;
template<class DataType>
class SeqStack
{
public:
SeqStack();
~SeqStack(){}
void Push(DataType x);
DataType Pop();
DataType GetTop();
int Empty();
private:
DataType data[StackSize];
int top;
};
#include<iostream>
using namespace std;
template<class DataType>
SeqStack<DataType>::SeqStack()
{
top=-1;
}
template<class DataType>
void SeqStack<DataType>::Push(DataType x)
{
if(top==StackSize-1)throw"上溢";
top++;
data[top]=x;
}
template<class DataType>
DataType SeqStack<DataType>::Pop()
{
DataType x;
if(top==-1)throw"下溢";
x=data[top--];
return x;
}
template<class DataType>
DataType SeqStack<DataType>::GetTop()
{
if(top!=-1)
return data[top];
}
template<class DataType>
int SeqStack<DataType>::Empty()
{
if(top==-1)return 1;
else return 0;
}
int main()
{
SeqStack<int>S;
if(S.Empty())
cout<<"栈为空"<<endl;
else
cout<<"栈为满"<<endl;
cout<<"对15和10执行入栈操作"<<endl;
S.Push(15);
S.Push(10);
cout<<"栈顶元素为"<<endl;
cout<<S.GetTop()<<endl;
cout<<"执行一次出栈操作"<<endl;
S.Pop();
cout<<"栈顶元素为:"<<endl;
cout<<S.GetTop()<<endl;
}
#include<iostream>
using namespace std;
template<class DataType>
struct Node
{
DataType data;
Node<DataType> *next;
};
template<class DataType>
class LinkStack
{
public:
LinkStack();
~LinkStack(){}
void Push(DataType x);
DataType Pop();
DataType GetTop();
int Empty();
private:
Node<DataType> *top;
};
template<class DataType>
LinkStack<DataType>::LinkStack()
{
top=new Node<DataType>;
top=NULL;
}
template<class DataType>
void LinkStack<DataType>::Push(DataType x)
{
Node<DataType>*s;
s=new Node<DataType>
;s->data=x;
s->next=top;
top=s;
}
template<class DataType>
DataType LinkStack<DataType>::Pop()
{
if(top==NULL)throw"下溢";
else{
Node<DataType>*p;
p=new Node<DataType>;
p=top;
DataType x=p->data;
top=top->next;
delete p;
return x;}
}
template<class DataType>
DataType LinkStack<DataType>::GetTop()
{
if(top!=NULL)
return top->data;
}
template<class DataType>
int LinkStack<DataType>::Empty()
{
if(top==NULL){
return 1;
}
else
{
return 0;
}
}
int main()
{
LinkStack<int>S;
if(S.Empty())
cout<<"栈为空"<<endl;
else
cout<<"栈为满"<<endl;
cout<<"对15和10执行入栈操作"<<endl;
S.Push(15);
S.Push(10);
cout<<"栈顶元素为"<<endl;
cout<<S.GetTop()<<endl;
cout<<"执行一次出栈操作"<<endl;
S.Pop();
cout<<"栈顶元素为:"<<endl;
cout<<S.GetTop()<<endl;
}
五、实验运行结果
顺序栈
链栈
六、实验总结和心得
栈的顺序存储结构称为顺序栈,顺序栈本质上是顺序表的简化。通常把数组中下标为0的一端作为栈底,同时附设
指针top指示栈顶元素在数组中的位置。栈的链接存储结构称为链栈,通常用单链表表示,并且不用附加头结点。
两者的时间性能都是常数时间O(1),唯一区别就是空间性能。实验时,在写出顺序栈后,参照书本就自然的把链栈
就改出来了,可是没有能够理解他们的本质。