c++栈
程序员文章站
2022-03-25 16:50:06
...
栈stack.h
#ifndef _STACK_
#define _STACK_
#include<vector>
#include<iostream>
using std::cout;
using std::vector;
template<class T>
class Stack
{
public:
Stack(const vector<T>& vec1);
bool isEmpty()const;
T Pop();
void push(const T& value);
void print()const;
private:
vector<T> vec;
int pop;
int size;
};
template<class T>
Stack<T>::Stack(const vector<T>&vec1) {
vec = vec1;
size = vec1.size();
pop = vec1.size()-1;
}
template<class T>
bool Stack<T>::isEmpty()const {
if (size = 0)
return true;
else
return false;
}
template<class T>
T Stack<T>::Pop() {
if (size>0) {
pop--;
size--;
return vec[pop + 1];
}
}
template<class T>
void Stack<T>::push(const T&value) {
if (vec.size() >size) {
vec[pop + 1] = value;
pop++;
size++;
}
else {
vec.push_back(value);
pop++;
size++;
}
}
template<class T>
void Stack<T>::print()const {
for (int i = 0; i < size; i++) {
cout << vec[i] << " ";
}
}
#endif // !_STACK_
测试 main.cpp
#include"stack.h"
int main()
{
vector<int> vec(10, 1);
Stack<int> stack(vec);
stack.push(20);
stack.Pop();
stack.print();
system("pause");
}