【C++】linkedStack類的實現
阿新 • • 發佈:2021-02-18
技術標籤:# 資料結構和演算法分析
linkedStack.h :
#pragma once
#include"chainNode.h"
#include<iostream>
using namespace std;
template<class T>
class linkedStack
{
private:
chainNode<T>* stackTop;//棧頂指標
int stackSize; //棧中元素個數
public:
linkedStack(int initialCapacity = 10)
{
stackTop = NULL;
stackSize = 0;
}
~linkedStack();
bool empty()const {
return stackSize == 0;
}
int size()const {
return stackSize;
}
void pop();
void push(const T& theElement) {
stackTop = new chainNode<T>(theElement, stackTop);
stackSize++;
}
T& top()const {
return stackTop- >element;
}
};
template<class T>
inline linkedStack<T>::~linkedStack()
{
while (stackTop != NULL)
{
chainNode<T>* nextNode = stackTop->next;
delete stackTop;
stackTop = nextNode;
}
}
template<class T>
inline void linkedStack<T>::pop()
{
if (empty()) {
cout << "棧為空,無法出棧";
return;
}
else {
chainNode<T> *nextNode = stackTop->next;
delete stackTop;
stackTop = nextNode;
stackSize--;
}
}
Test.cpp:
#include<iostream>
using namespace std;
#include"linkedStack.h"
int main() {
linkedStack<int> s;
// add a few elements
s.push(1);
s.push(2);
s.push(3);
s.push(4);
cout << "Stack should be 1234, bottom to top" << endl;
// test empty and size
if (s.empty())
cout << "The stack is empty" << endl;
else
cout << "The stack is not empty" << endl;
cout << "The stack size is " << s.size() << endl;
while (!s.empty())
{
cout << "Stack top is " << s.top() << endl;
s.pop();
cout << "Popped top element" << endl;
}
s.pop();
return 0;
}