Stack.h
#pragma once
template <class T>
class Stack {
public:
virtual void clear() = 0; // clean the stack
virtual void push(const T&) = 0; // push T into stack
virtual void pop() = 0; // pop top item in stack
virtual T& top() = 0; // return the top item reference
virtual bool empty() = 0; // is stack empty?
virtual bool full() = 0; // is stack full?
};
LinkStack.h
#pragma once
#include <iostream>
#include <exception>
#include "Stack.h"
template <class T>
class Node {
public:
T val;
Node* next;
Node(const T& val, Node* p = nullptr)
:val(val), next(p) {}
Node(Node* p = nullptr)
:next(p) {}
};
template <class T>
class LinkStack : public Stack<T> {
public:
LinkStack(size_t stackSize = 1024)
:stackTop(nullptr), size(0), Maxsize(stackSize) {}
~LinkStack() {
clear();
}
virtual void clear() override {
while (stackTop != nullptr) {
Node<T>* tmp = stackTop;
pop();
delete tmp;
}
size = 0;
return;
}
virtual void push(const T& val) override {
checkOverFlow();
stackTop = new Node<T>(val, stackTop);
++size;
return;
}
virtual void pop() override {
checkUnderFlow();
Node<T>* tmp = stackTop;
stackTop = stackTop->next;
delete tmp;
--size;
return;
}
virtual T& top() override{
checkUnderFlow();
return stackTop->val;
}
virtual bool empty() override {
return size == 0;
}
virtual bool full() override {
return size == Maxsize;
}
void showStack() {
while (!empty()) {
std::cout << "Stack current top value is " << top() << std::endl;
pop();
}
return;
}
private:
Node<T>* stackTop;
size_t size;
size_t Maxsize;
void checkUnderFlow() {
if (empty()) {
throw std::exception("Stack underflow");
}
return;
}
void checkOverFlow() {
if (size + 1 > Maxsize) {
throw std::exception("Stack overflow");
}
return;
}
};
main.cpp
// LinkStack.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include "LinkStack.h"
int factorial(int val) {
long result = 1;
LinkStack<int> s(1024);
while (val) {
int tmp = val--;
s.push(tmp);
}
while (!s.empty()) {
result *= s.top();
s.pop();
}
return result;
}
int main()
{
try {
std::cout << "Enter the size of stack" << std::endl;
int size;
std::cin >> size;
LinkStack<int> s(size);
while (size--) {
std::cout << "Enter the value be pushed into stack" << std::endl;
int val;
std::cin >> val;
s.push(val);
}
s.showStack();
std::cout << "Enter the value you want calculate factorial" << std::endl;
int fac;
std::cin >> fac;
std::cout << "The factorial is " << factorial(fac) << std::endl;
return 0;
}
catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
catch (...) {
throw;
}
}