stack.h
#ifndef STACK_H_
#define STACK_H_
#include<iostream>
template<class T>
struct Node
{
T data;
Node<T>* next;
};
template<class T>
class Stack
{
private:
Node<T>* top;
public:
Stack() { top = nullptr; }
~Stack();
void Push(T x);
void Pop();
T GetTop();
bool Empty();
void Print();
};
template<class T>
Stack<T>::~Stack()
{
Node<T>* p = top;
while (p)
{
top = p;
p = p->next;
delete top;
}
}
template<class T>
void Stack<T>::Push(T x)
{
Node<T>* p = new Node<T>;
p->data = x;
p->next = top;
top = p;
}
template<class T>
void Stack<T>::Pop()
{
if (Empty())throw"Empty";
Node<T>* temp = top;
top = top->next;
delete temp;
}
template<class T>
T Stack<T>::GetTop()
{
return top->data;
}
template<class T>
bool Stack<T>::Empty()
{
return (top == nullptr ? true : false);
}
template<class T>
void Stack<T>::Print()
{
Node<T>* p = top;
while (p)
{
std::cout << p->data << " ";
p = p->next;
}
std::cout << std::endl;
}
#endif // !STACK_H_
UseStack.cpp
#include<iostream>
#include"stack.h"
int main()
{
using std::cout;
using std::endl;
Stack<int> P1;
for (int i = 1; i <= 10; i++)
{
P1.Push(i);
}
if (P1.Empty())
{
std::cout << "empty\n";
}
else
{
cout << "原有:\n";
P1.Print();
P1.Pop();
cout << "After Delete:\n";
P1.Print();
cout << "栈顶:" << P1.GetTop();
}
return 0;
}