栈的实现
node.h
#ifndef UNTITLED_NODE_H
#define UNTITLED_NODE_H
template<class T>
struct Node{
T data;//数据域
Node<T> * next;//指针域
Node(){//无参的构造函数
next = NULL;
}
Node(T item,Node<T> * link=NULL){//已知数据元素值和指针建立结点
data=item;
next=link;
}
};
#endif //UNTITLED_NODE_H
stack.h
#ifndef UNTITLED_STACK_H
#define UNTITLED_STACK_H
#include "node.h"
#define STACK_SIZE 10000
template<class T>
class Stack{
public:
Stack(){};
virtual ~Stack(){};
virtual bool Push(const T &e)=0;
virtual bool Pop(T &e)=0;
virtual bool GetTop(T &e) const = 0;
};
//顺序栈
template <class T>
class SqStack:public Stack<T>{
private:
T elem[STACK_SIZE];//储存栈元素值
int top;//栈顶
public:
SqStack(){
top = -1;
};
~SqStack(){};
bool Push(const T &e){
if(top==STACK_SIZE-1)//栈满
return false;
else{
elem[++top] = e;
return true;
}
}
bool Pop(T &e){
if(top==-1)//栈空
return false;
else{
e = elem[top--];
return true;
}
}
bool GetTop(T &e) const{//取出栈顶元素
if(top==-1)
return false;
else{
e=elem[top];
return true;
}
}
};
//链式栈
template<class T>
class LinkStack:public Stack<T>{
private:
Node<T> * top;//栈顶指针
public:
LinkStack(){
top=NULL;
};
~LinkStack(){
T e;//临时变量
while(top != NULL)
Pop(e);
};
bool Push(const T &e){
top = new Node<T>(e,top);//top指向下一结点
return true;
}
bool Pop(T &e){
if(top==NULL)
return false;
else{
e=top->data;
Node<T> *p=top;
top=top->next;
delete p;
return true;
}
}
bool GetTop(T &e) const{
if(top==NULL)
return false;
else{
e=top->data;
return true;
}
}
};
#endif //UNTITLED_STACK_H
main.cpp
#include <iostream>
using namespace std;
#include "stack.h"
int main(){
int select = 0;
Stack<int> * pStack;//指向栈的指针
int e;//元素
do{
cout<<"请选择1:测试顺序栈,2:测试链式栈"<<endl;
cin>>select;//输入选择
}while(select!=1 && select!=2);
if(select==1)
pStack=new SqStack<int>;
else
pStack=new LinkStack<int>;
while(select!=5){
cout<<"1生成栈"<<endl;
cout<<"2入栈"<<endl;
cout<<"3出栈"<<endl;
cout<<"4取栈顶"<<endl;
cout<<"5退出"<<endl;
cout<<"选择功能1-5";
cin>>select;
switch(select){
case 1://生成栈
cout<<"输入e(e=0退出)";
cin>>e;
while(e!=0){
pStack->Push(e);
cin>>e;
}
break;
case 2://入栈
printf("输入元素值:");
cin>>e;
pStack->Push(e);
break;
case 3://出栈
pStack->Pop(e);
cout<<"栈顶元素值为"<<e<<endl;
break;
case 4://取栈顶
pStack->GetTop(e);
cout<<"栈顶元素值为"<<e<<endl;
break;
}
}
delete pStack;
return 0;
}```
text中
include_directories(/Users/tanshushu/CLionProjects/untitled/stack.h)
include_directories(/Users/tanshushu/CLionProjects/untitled/node.h)