資料結構實驗2
阿新 • • 發佈:2018-12-03
一、順序棧的實現:
#include<iostream> using namespace std; #include "SeqStack.cpp" void 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"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"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; }
二、鏈棧的實現
#ifndef LinkStack
#define LinkStack
typedef int dataType;
struct node
{
dataType data;
node *next;
};
class ls
{
public:
ls();
~ls();
void push(dataType var);
void pop(); dataType stackTop();
bool isEmpty();
private:
node *top; };
#endif
#include <iostream>
#include "LinkStack.h"
using namespace std;
ls::ls()
{
top = NULL;
}
ls::~ls()
{
node *ptr = NULL;
while(top != NULL)
{
ptr = top->next;
delete top;
top = ptr;
}
}
void ls::push(dataType var)
{
node *ptr = new node;
ptr->data = var;
ptr->next = top;
top = ptr;
}
void ls::pop()
{
node *ptr = top->next;
delete top;
top = ptr;
}
dataType ls::stackTop()
{
return top->data;
}
bool ls::isEmpty()
{
return top == NULL;
}
#include <iostream>
#include "LinkStack.h"
using namespace std;
int main()
{
ls l;
cout<<"對15和10 進行入棧操作"<<endl;
l.push(15);
l.push(10);
cout<<"執行一次出棧從操作"<<endl;
l.pop();
return 0;
}