一、普通类实现int类型栈
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
class myStack
{
private:
int* items;
int stack_size;
int top;
public:
myStack(int _stack_size): stack_size(_stack_size), top(0)
{
items = new int[stack_size + 1];
}
~myStack()
{
delete[] items; items = nullptr;
}
bool isEmpty() const
{
return top == 0;
}
bool isFull() const
{
return top == stack_size;
}
bool push(const int& val)
{
if (top < stack_size)
{
items[++ top] = val;
return true;
}
return false;
}
bool pop(int& val)
{
if (top == 0) return false;
val = items[top -- ];
return true;
}
};
int main()
{
myStack stk(5);
stk.push(7), stk.push(4), stk.push(9), stk.push(78), stk.push(1);
cout << stk.isFull() << endl;
int item = 0;
stk.pop(item);
cout << item << endl;
return 0;
}
二、模板类
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
template <class DataType>
class myStack
{
private:
DataType* items;
int stack_size;
int top;
public:
myStack(int _stack_size): stack_size(_stack_size), top(0)
{
items = new DataType[stack_size + 1];
}
~myStack()
{
delete[] items; items = nullptr;
}
bool isEmpty() const
{
return top == 0;
}
bool isFull() const
{
return top == stack_size;
}
bool push(const DataType& val)
{
if (top < stack_size)
{
items[++ top] = val;
return true;
}
return false;
}
bool pop(DataType& val)
{
if (top == 0) return false;
val = items[top -- ];
return true;
}
};
int main()
{
myStack<string> stk(5);
stk.push("冰魄"), stk.push("天行者"), stk.push("源极之星"), stk.push("流火"), stk.push("裁决者");
cout << stk.isFull() << endl;
string item;
stk.pop(item);
cout << item << endl;
return 0;
}