#include <cstdlib>
#include <iostream>
using namespace std;
// 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(); // 若栈已满返回真
};
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(int defSize) { // 构造函数
top = NULL;
size = 0;
}
~lnkStack() { // 析构函数
clear();
}
void clear() { // 清空栈内容
while (top != NULL) {
Link<T> *tmp = top;
top = top->next;
delete tmp;
}
size = 0;
}
bool push(const T item) { // 入栈操作的链式实现
Link<T>* tmp = new Link<T>(item, top);
top = tmp;
size++;
return true;
}
bool 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;
}
bool getTop(T* item) { // 返回栈顶内容,但不弹出
if (size == 0) {
cout << "栈为空,不能出栈操作"<< endl;
return false;
}
*item = top->data;
return true;
}
};
long f(long n);
int main(int argc, char *argv[])
{
Link<int>* test = new Link<int>(10, NULL);
cout << test->data << endl;
long x, m;
cin >> x;
cout << "the factioral of "
<< x
<< " is " ;
m = f(x);
cout << m
<<endl;
cin >> x;
}
// nonrevursive with stack
long f(long n) {
lnkStack<long> s(0);
long tmp;
long m = 1;
while (n > 1) { // 不满足递归出口
s.push(n);
n--;
} // 按递归规则把相应数据压栈
while(s.pop(&tmp)) // 递归出口满足,开始进行返回处理
m *= tmp;
return m ;
}
09-24
120
05-31
05-31
05-31
05-31
05-31
05-31
05-31
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交