上代码:
#ifndef C__CODE_STACK_LINK_H
#define C__CODE_STACK_LINK_H
#include <iostream>
using namespace std;
template<class T>
struct stack_link{
T data;
stack_link<T>* link;
stack_link(){
link= nullptr;
}
stack_link(T x){
link= nullptr;
data=x;
}
};
template<class T>
class Stack{
private:
stack_link<T>* top;
stack_link<T>* bottom;
void rout();
protected:
void destroy();
public:
Stack(){
top=new stack_link<T>;
bottom=top;
}
Stack(T x){
top=new stack_link<T>(x);
bottom=top;
}
~Stack(){
destroy();
}
bool push(T x);
bool pop();
T Top();
void out(){
rout();
}
stack_link<T>* getTop();
bool isempty(){
return top== nullptr;
}
};
template<class T>
void Stack<T>::destroy() {
while(top!=bottom){
stack_link<T>* current=top;
top=top->link;
current->link= nullptr;
delete current;
}
top= nullptr;
delete top;
delete bottom;
}
template<class T>
bool Stack<T>::push(T x) {
if(!top){
top=new stack_link<T>(x);
return true;
}
else
{
stack_link<T>* current=new stack_link<T>(x);
current->link=top;
top=current;
current= nullptr;
delete current;
return true;
}
}
template<class T>
bool Stack<T>::pop() {
stack_link<T>* current=top;
top=top->link;
current= nullptr;
delete current;
return true;
}
template<class T>
T Stack<T>::Top() {
if(top->link!= nullptr)return top->data;
}
template<class T>
stack_link<T> *Stack<T>::getTop() {
if(!isempty())return top;
else return nullptr;
}
template<class T>
void Stack<T>::rout() {
stack_link<T>* ptr=top;
while (ptr!=bottom){
cout<<ptr->data<<"->";
ptr=ptr->link;
}
cout<<ptr->data;
ptr= nullptr;
delete ptr;
}
#endif //C__CODE_STACK_LINK_H
测试代码:
#include <iostream>
#include "Stack_Link.h"
using namespace std;
int main(){
Stack<int>s(1);
for(int i=2;i<20;i++)
s.push(i);
cout<<s.Top()<<endl;
s.pop();
s.out();
return 0;
}
结果:
写在后面:
实现方法基本参照单链表,开始写代码时退出代码是一个无序值,通过调试后找出一些调用方法中定义后没有及时删除的指针,最后代码暂时没发现其它错误。