hpp
#pragma once
#include<iostream>
#include<string>
using namespace std;
template<class T>
struct StNode
{
public:
T data;
StNode<T>* next;
};
template<class T>
class LinkStack
{
private:
//栈顶指针
StNode<T>* top;
public:
LinkStack();
LinkStack(LinkStack& ls);
~LinkStack();
int Length();
bool empty();
void clear();
bool push(T e);
bool pop(T &e);
bool getTop(T& e);
};
cpp
#include"链栈.hpp"
#include<iostream>
#include<string>
using namespace std;
template<class T>
LinkStack<T>::LinkStack()
{
this->top = NULL;
}
template<class T>
LinkStack<T>::LinkStack(LinkStack& st)
{
StNode<T>* p,*q,*pre;
p = new StNode<T>;
this->top = p;
q = st.top;
while (q != NULL)
{
pre = new StNode<T>;
p->next = pre;
p->data = q->data;
p = pre;
delete pre;
q = q->next;
}
p->next = NULL;
}
template<class T>
LinkStack<T>::~LinkStack()
{
cout << "调用析构函数" << endl;
StNode<T>* p;
while (top != NULL)
{
p = top;
top = p->next;
delete p;
}
}
template<class T>
int LinkStack<T>::Length()
{
int count = 0;
StNode<T>* p;
p = this->top;
while (p != NULL)
{
p = p->next;
count++;
}
return count;
}
template<class T>
bool LinkStack<T>::empty()
{
return this->top == NULL;
}
template<class T>
void LinkStack<T>::clear()
{
StNode<T>* p;
while (top != NULL)
{
p = top;
top = top->next;
delete p;
}
}
template<class T>
bool LinkStack<T>::push(T e)
{
StNode<T>* p = new StNode<T>;
p->next = top;
top = p;
p->data = e;
return true;
}
template<class T>
bool LinkStack<T>::pop(T& e)
{
if (top == NULL)
{
return false;
}
StNode<T>* old_Top;
old_Top = top;
e = this->top->data;
top = top->next;
delete old_Top;
return true;
}
template<class T>
bool LinkStack<T>::getTop(T& e)
{
if (top == NULL)
return false;
e = top->data;
return true;
}
int main()
{
LinkStack<int>a;
for (size_t i = 0; i < 5; i++)
{
a.push(i);
}
LinkStack<int>b(a);
int t;
b.getTop(t);
//int t;
//t = a.Length();
a.getTop(t);
//a.clear();
//t = a.Length();
cout << t << endl;
system("pause");
return 0;
}