您的位置:首页 > 其它

实验三、顺序栈和链栈

2017-10-24 22:46 225 查看
一、实验目的

1、 熟练掌栈的结构特点,掌握栈的顺序存储和链式存储结构和实现。

2、 学会使用栈解决实际问题。

二、实验内容

1、自己确定结点的具体数据类型和问题规模:

分别建立一个顺序栈和链栈,实现栈的压栈和出栈操作。

三、代码

链栈

#ifndef LinkStack_H
#define LinkStack_H
template<class DataType>
class LinkStack
{
public:
LinkStack(){top=NULL;}
~LinkStack();
void Push(DataType x);
DataType Pop();
DataType GetTop();{if(top!=NULL)return top->data;}
int Empty(){top==NULL?return 1;return 0;}
private:
Node<DataType>*top;
};
#endif;

#include"LinkStack.h"

template<class DataType>
LinkStack<DataType>::LinkStack()
{
top=NULL;
}

template<class DataType>
void LinkStack<DataType>::Push(DataType x)
{
s=new Node;s->data=x;
s->next=top;top=s;
}

template<class DataType>
DataType LinkStack<DataType>::Pop()
{
if(top==NULL)throw"下溢";
x=top->data;p=top;
top=top->next;
delete p;
return x;
}

template<class DataType>
DataType LinkStack<DataType>::GetTop()
{
if(top!=NULL)
return data[top];
}

template<class DataType>
int LinkStack<DataType>::Empty()
{
if(top==NULL)return 1;
else return 0;
}

#include<iostream>
using namespace std;
#include"LinkStack"

void main()
{
LinkStack<int> L;
if(L.Empty())
cout<<"栈为空"<<endl;
else
cout<<"栈非空"<<endl;
cout<<"对8和6执行入栈操作"<<endl;
L.Push(8);
L.Push(6);
cout<<"栈顶元素为:"<<endl;
cout<<L.GetTop()<<endl;
cout<<"执行依次出栈操作"<<endl;
L.Pop();
cout<<"栈顶元素为:"<<endl;
cout<<L.GetTop()<<endl;
}


顺序栈

#ifndef SeqStack_H
#define SeqStack_H
const int StackSize=100;
template<class DataType>
class SeqStack
{
public:
SeqStack();
~SeqStack(){}
void Push(DataType x);
DataType Pop();
DataType GetTop();
int Empty;
private:
DataType data[StackSize];
int top;
};
#endif

#include"SeqStack.h"

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;
}

#include<iostream>
using namespace std;
#include"SeqStack.cpp"

void main()
{
SeqStack<int> S;
if(S.Empty())
cout<<"栈为空"<<endl;
else
cout<<"栈非空"<<endl;
cout<<"对8和6执行入栈操作"<<endl;
S.Push(8);
S.Push(6);
cout<<"栈顶元素为:"<<endl;
cout<<S.GetTop()<<endl;
cout<<"执行一次出栈操作"<<endl;
S.Pop();
cout<<"栈顶元素为:"<<endl;
cout<<S.GetTop()<<endl;
}


四、运行结果

四、运行结果

链栈:

链栈为空

对8和6入栈

栈顶元素为:

8

进行一次出栈

栈顶元素为:

6

Press any key to continue

顺序栈:

栈为空

对8和6执行入栈操作

栈顶元素为:

8

执行一次出栈操作

栈顶元素为:

6

Press any key to continue

五、心得与总结

通过这次实验,我对链栈和顺序栈有了进一步了解。实验过程中,依然无法完全自主完成,仍然需要借助书本来完成实验。但试验过后对链栈和顺序栈掌握得更清晰。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: