Files
Data-Structure/LinearList/Stack/chainStack/chainStack.h
2025-07-30 14:33:09 +08:00

128 lines
2.1 KiB
C++

#ifndef CHAIN_STACKH
#define CHAIN_STACKH
#include <iostream>
#include "stack.h"
#include "node.h"
template <class T>
class chainStack : public Stack<T>{
private:
Node<T>* first;
Node<T>* last;
int stackTop;
public:
chainStack() = delete;
chainStack(Node<T>* f = nullptr);
chainStack(const chainStack<T>& x);
virtual bool empty() const;
virtual int size() const;
virtual T& top();
virtual void pop();
virtual void push(const T& theElement);
virtual void show() const;
~chainStack();
};
template <class T>
inline chainStack<T>::chainStack(Node<T>* f) :first(f), stackTop(0), last(nullptr) {
Node<T>* p = first;
while (p) {
++stackTop;
p = p->next;
}
}
template <typename T>
inline chainStack<T>::chainStack(const chainStack<T>& x)
{
Node<T>* run = x.first;
Node<T>* tnext = nullptr;
Node<T>* tprev = nullptr;
while (run) {
Node<T>* tmp = new Node<T>(run->element, tprev, tnext);
if(tprev) tprev->next = tmp;
if (!tprev) first = tmp;
tprev = tmp;
run = run->next;
}
last = tprev;
}
template<class T>
inline bool chainStack<T>::empty() const
{
return (stackTop == 0);
}
template<class T>
inline int chainStack<T>::size() const
{
return stackTop;
}
template<class T>
inline T& chainStack<T>::top()
{
return last->element;
}
template<class T>
inline void chainStack<T>::pop()
{
if (stackTop == 0)
throw std::invalid_argument("Pop Error: No Element in Stack");
if (last) {
Node<T>* tmp = last;
last = last->prev;
if (last) {
last->next = nullptr;
}
else {
first = nullptr;
}
delete tmp;
stackTop--;
}
}
template<class T>
inline void chainStack<T>::push(const T& theElement) {
Node<T>* tmp = new Node<T>(theElement, last, nullptr);
if (last) last->next = tmp;
else first = tmp;
last = tmp;
stackTop++;
}
template<class T>
inline void chainStack<T>::show() const {
Node<T>* p = first;
while (p) {
std::cout << p->element << " ";
p = p->next;
}
std::cout << std::endl;
}
template<class T>
inline chainStack<T>::~chainStack()
{
Node<T>* p = first;
Node<T>* that;
while (p) {
that = p;
p = that->next;
delete that;
}
first = nullptr;
last = nullptr;
stackTop = 0;
}
#endif // !CHAIN_STACKH