1、数组实现栈(加了模板)
#include <iostream>
using namespace std;
#define MAX 100
//数组实现栈:模板类
template<class T>
class MyStack
{
public:
T * buf;
T top;
public:
MyStack(){
buf = new T[MAX];
top = -1;
}
~MyStack(){
delete [] buf;
buf = NULL;
cout<<"release buf"<<endl;
}
bool isempty();
bool isfull();
void push(T a);
T pop(); //返回栈顶元素
};
template<class T>
bool MyStack<T>::isempty(){
if(top==-1)
return true;
return false;
}
template<class T>
bool MyStack<T>::isfull(){
if(top==MAX-1)
return true;
return false;
}
template<class T>
void MyStack<T>::push(T a){
if(isfull()){
return;
}
top++;
buf[top] = a;
}
template<class T>
T MyStack<T>::pop(){
if(isempty()){
return -1;
}
top--;\
return buf[top];
}
int main ()
{
MyStack<int> *mystack =new MyStack<int>();
mystack->push(5);
mystack->push(4);
mystack->push(3);
cout<<"top is : "<<mystack->pop()<<endl;
for(int i=mystack->top;i>=0;i--){
cout<<mystack->buf[i]<<endl;
}
delete mystack; //调用析构函数,释放内存
mystack = NULL; //将指针指向NULL 否则将成为野指针
return 0;
}
2、链表实现栈
#include <iostream>
#include <stack>
using namespace std;
//单向链表节点
struct ListNode{
int value;
struct ListNode *Next;
};
class MyStack
{
public: //成员变量位置
ListNode *Head;
public: //成员函数位置
MyStack(){
Head = new ListNode; //创建对象的时候调用
}
~MyStack(){ //析构函数一般用于释放内存
delete Head;
Head = NULL;
}
bool isempty();
void pushback(int n);
void pop();
void egrodic();
};
bool MyStack::isempty(){
ListNode *P = Head;
if(P==NULL||P->Next==NULL)
return true;
return false;
}
void MyStack::pushback(int n){
ListNode *P = Head;
while(P->Next!=NULL){
P = P->Next;
}
ListNode *tmp = new ListNode;
tmp->value = n;
tmp->Next =NULL;
P->Next = tmp;
P = tmp;
}
void MyStack::pop(){
if(isempty())
return;
ListNode *P = Head;
while(P->Next->Next!=NULL){
P = P->Next;
}
P->Next = NULL;
}
void MyStack::egrodic(){
if(isempty())
return;
ListNode *P = Head;
while(P->Next!=NULL){
P = P->Next;
cout<<P->value<<endl;
}
}
int main ()
{
MyStack *mystack = new MyStack; //自己定义一个对象
mystack->pushback(2);
mystack->pushback(3);
mystack->pushback(4);
mystack->pop();
mystack->egrodic();
delete mystack;
mystack = NULL;
return 0;
}