C++语言实现链式栈
头文件:
#pragma once
#include<iostream>
#include<exception>
using namespace std;
template<typename T>
struct Node {
T data = T();
Node<T>* next = nullptr;
};
template<typename T>
class LinkStack {
public:
~LinkStack();
LinkStack();
bool is_Empty()const; //判断栈是否为空。
bool enterStack(const T& t); //入栈。
bool exitStack(); //出栈。
void display()const;
private:
Node<T>* head = nullptr;
};
CPP文件:
#include"LinkStack.h"
template<typename T>
LinkStack<T>::~LinkStack()
{
Node<T>* tmp1 = head, * tmp2 = nullptr;
while (tmp1){
tmp2 = tmp1;
tmp1 = tmp1->next;
delete tmp2;
}
}
template<typename T>
LinkStack<T>::LinkStack():head(nullptr)
{
}
template<typename T>
bool LinkStack<T>::is_Empty() const
{
if (!head) return true;
return false;
}
template<typename T>
bool LinkStack<T>::enterStack(const T& t)
{
//让tmp指向首节点。
Node<T>* tmp = head;
//让头指针指向新元素。
head = new Node<T>;
if (!head) return false;
head->data = t;
head->next = tmp;
return true;
}
template<typename T>
bool LinkStack<T>::exitStack()
{
Node<T>* tmp = head;
if (!head) return false;
head = head->next;
delete tmp;
return true;
}
template<typename T>
void LinkStack<T>::display() const
{
Node<T>* tmp = head;
while (tmp) {
cout << tmp->data << " ";
tmp = tmp->next;
}
cout << endl;
}