c++中顺序栈的封装
栈是一种先入后出的线性数据结构,分为顺序栈和链栈。本博文主要是顺序栈的封装
static.h
#ifndef _stack_H
#define _stack_H
#include <iostream>
#include <malloc.h>
typedef int ElemType;
class Stack
{
ElemType *arr;
int s_top;
size_t capacity;
public:
size_t GetCapacity() const;
size_t size() const;
bool isFull() const;
bool empty() const;
void push(const ElemType x);
void pop();
ElemType top() ;
void clear();
Stack(size_t n);
~Stack();
};
#endif
static.cpp
#include "2_stack.h"
size_t Stack::GetCapacity() const
{
return capacity;
}
size_t Stack::size() const
{
return s_top + 1;
}
bool Stack::isFull() const
{
return size() == capacity;
}
bool Stack::empty() const
{
return s_top == -1;
}
void Stack::push(const ElemType x)
{
if(isFull())
{
std::cout << "The stack is full." << std::endl;
return;
}
arr[++s_top] = x;
}
void Stack::pop()
{
if (empty())
{
std::cout << "The stack is empty." << std::endl;
return;
}
s_top--;
}
ElemType Stack::top()
{
if (empty())
{
std::cout << "The queue is empty." << std::endl;
return -1;
}
return arr[s_top];
}
void Stack::clear()
{
s_top = -1;
}
Stack::Stack(size_t n)
: s_top(-1), capacity(n)
{
arr = (ElemType*)malloc(sizeof(ElemType) * n);
}
Stack::~Stack()
{
free(arr);
arr = nullptr;
}
main.cpp
#include "2_stack.h"
#include <iostream>
using namespace std;
int main()
{
Stack obj(10);
for(int i=0;i<9;i++)
{
if(obj.isFull()!=0)
{
cout<<"栈满"<<endl;
return -1;
}
obj.push(i);
}
for(int i=0;i<9;i++)
{
cout<< obj.top()<<endl;
obj.pop();
}
}