类对栈实现的封装
主函数
#include "stdafx.h"
#include "Stack.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
Stack st;
st.init();
for (char v = 'a'; !st.isFull() && v != 'z'+1; v++)
{
st.push(v);
}
while (!st.isEmpty())
cout << st.pop() << endl;
return 0;
}
Stack.h
#pragma once
class Stack
{
public:
void init(); //可以用构造器代替
bool isEmpty();
bool isFull();
char pop();
void push(char c); //c是指要插入的数据
private:
char space[1024]; //栈大小
int top; //栈的下标
};
stack.cpp
#include "Stack.h"
#include <iostream>
using namespace std;
void Stack::init() //初始化
{
top = 0;
memset(space, 0, 1024);//将空间里的内容进行清0
}
bool Stack::isEmpty()
{
return top == 0;
//相当于将top和0比较 如果相等 返回true不等返回false
}
bool Stack::isFull()
{
return top == 1024;
}
char Stack::pop() //出栈返回相应数据
{
return space[--top];
//出栈时先将下标(也就是指针)向下移 让其
//指向第一个要出栈的数据 然后在进行出栈
}
void Stack::push(char c) //进栈
{
space[top++] = c;
//进栈时是将数据先放入后 下标(指针)在++向上移动
}