實驗三、順序棧和鏈棧
阿新 • • 發佈:2019-02-01
一、實驗目的
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
五、心得與總結
通過這次實驗,我對鏈棧和順序棧有了進一步瞭解。實驗過程中,依然無法完全自主完成,仍然需要藉助書本來完成實驗。但試驗過後對鏈棧和順序棧掌握得更清晰。