myStack.h
//myStack.h
// abstract data type for stack
template <class T> // 栈的元素类型为 T
class Stack {
public: // 栈的运算集
void clear(); // 变为空栈
bool push(const T item); // item入栈,成功则返回真,否则返回假
bool pop(T* item); // 返回栈顶内容并弹出,成功返回真,否则返回假,
bool getTop(T* item); // 返回栈顶内容但不弹出成功返回真,否则返回假,
bool isEmpty(); // 若栈已空返回真
bool isFull(); // 若栈已满返回真
};
lnkStack.h
//lnkStack.h
#include <cstdlib>
#include <iostream>
#include "myStack.h"
using namespace std;
template <class T>
class Link {
public:
T data; // 用于保存结点元素的内容
Link * next; // 指向后继结点的指针
Link(const T info, Link* nextValue) { // 具有两个参数的Link构造函数
data = info;
next = nextValue;
}
Link(Link* nextValue = NULL) { // 具有两个参数的Link构造函数
next = nextValue;
}
};
template <class T>
class lnkStack : public Stack <T> {
private: // 栈的链式存储
Link<T>* top; // 指向栈顶的指针
int size; // 存放元素的个数
public: // 栈运算的链式实现
lnkStack(); // 构造函数
~lnkStack(); // 析构函数
void clear(); // 清空栈内容
bool push(const T item); // 入栈操作的链式实现
bool pop(T* item); // 出栈的链式实现
bool getTop(T* item); // 返回栈顶内容,但不弹出
bool isEmpty();
};
template <class T>
lnkStack<T>::lnkStack()
{
top=NULL;
size=0;
}
template <class T>
lnkStack<T>::~lnkStack()
{
clear();
}
template<class T>
void lnkStack<T>::clear()
{
while(top!=NULL)
{
Link<T> * tmp=top;
top=top->next;
delete tmp;
}
size=0;
}
template<class T>
bool lnkStack<T>::push(const T item)
{
Link<T> * tmp=new Link<T>(item,top); //头插法
top=tmp;
size++;
return true;
}
template<class T>
bool lnkStack<T>::pop(T * item)
{
Link<T> * tmp;
if(size==0)
{
cout<<"栈为空,不能执行出栈操作"<<endl;
return false;
}
*item=top->data;
tmp=top->next;
delete top;
top=tmp;
size--;
return true;
}
template<class T>
bool lnkStack<T>::getTop(T * item)
{
if(size==0)
{
cout<<"栈为空,不能读取栈顶元素"<<endl;
return false;
}
*item=top->data;
return true;
}
main.cpp
//main.cpp
#include <cstdlib>
#include <iostream>
using namespace std;
#include "lnkStack.h"
using namespace std;
long fac(long n);
int main(int argc, char *argv[])
{
long result,n;
cout<<"请输入n的值:"<<endl;
cin>>n;
result=fac(n);
cout<<n<<"的阶乘为:"<<result<<endl;
return 0;
}
//利用链栈求阶乘
long fac(long n) {
long result=1;
long num;
lnkStack<long> lnk;
while(n>0)
{
lnk.push(n--);
}
while(lnk.pop(&num))
{
result*=num;
}
return result;
}