//链栈
template<class T>
struct node
{
node<T>* next;//链表指针域
T date;//数据域
};
template<class T>
class Stack
{
public:
Stack();//初始化栈
~Stack();//析构链栈
void pushstack(T date);//入栈
void print();//遍历栈
T popstack(T* date);//出栈
private:
int count;//记录结点个数
node<T>* phead;//头结点
};
template<class T>
T Stack<T>::popstack(T* date)//出栈
{
if (!phead->next)//无数据就不不给出栈
return 0;
node<T>* newnode = phead;
*date = newnode->next->date;
newnode->next = newnode->next->next;
return *date;
}
template<class T>
void Stack<T>::print()
{
node<T>*p = phead;
cout << "链栈元素为: ";
while (p->next != nullptr)
{
p = p->next;
cout << p->date << " ";
}
cout << endl;
}
template<class T>
void Stack<T>::pushstack(T date)
{
node<T>*cur = new node<T>;
cur->date = date;
cur->next = phead->next;
phead->next = cur;
++count;
}
template<class T>
Stack<T>::Stack()
{
phead = new node<T>;
phead->next = nullptr;
phead->date = 0;
count = 0;
cout << "初始化链栈完毕" << endl;
}
template<class T>
Stack<T>::~Stack()
{
//删除链表
node<T>* newnode = phead;
node<T>* p = nullptr;
while (newnode->next != nullptr)
{
p = newnode;
newnode = newnode->next;
delete p;
}
delete newnode;
newnode = nullptr;
cout << "删除链表成功" << endl;
}
int main()
{
Stack<int>s1;
s1.pushstack(1); s1.pushstack(2); s1.pushstack(3); s1.pushstack(4); s1.pushstack(5);
s1.print();
int i = 0;
s1.popstack(&i);
cout << i << endl;
s1.print();
return 0;
}