栈(一)—一种后进先出机制LIFO(last_in_first_out)
//visit() 适用于遍历自定义类,较复杂
- 栈的简单操作包括入栈、出栈、遍历等。和对列有很大相似性,只是头指针不再移动,永远是0,尾指针不断增加
- 栈模板代码:
//栈模板
#pragma once
#include<iostream>
#include<string>
using namespace std;
template<class T>
class MyStack
{
public:
MyStack(int size);//构造
~MyStack();//析构
bool s_empty();//判空
bool s_full();//判满
void s_in(T t);//进栈
void s_out();//出栈
void s_traverse(bool n);//遍历
void s_clear();//清空
int s_length();//长度
private:
T* sta;
int s_num;
int s_size;
};
template<class T>
MyStack<T>::MyStack(int size)
{
s_size = size;
s_num = 0;
sta = new T[size];
}
template<class T>
MyStack<T>::~MyStack()
{
delete []sta;
sta = NULL;
}
template<class T>
bool MyStack<T>::s_empty()//判空
{
return s_num == 0 ? true : false;
}
template<class T>
bool MyStack<T>::s_full()//判满
{
return s_num == s_size ? true : false;
}
template<class T>
void MyStack<T>::s_in(T t)//进栈
{
if (!s_full())
{
sta[s_num] = t;
s_num++;
}
else
{
cout << "Can not add any more ingredients!" << endl;
}
}
template<class T>
void MyStack<T>::s_out()//出栈
{
if (!s_empty())
{
s_num--;
cout << sta[s_num] << endl;
}
else
{
cout << "There is no ingredient!" << endl;
}
}
template<class T>
void MyStack<T>::s_traverse(bool n)
{
for (int i = 0; i < s_num; i++)
{
if (n)
{
cout << sta[(s_num-i-1)] << endl;
}
else
{
cout << sta[i] << endl;
}
}
}//遍历
template<class T>
void MyStack<T>::s_clear()
{
s_num = 0;
}//清空
template<class T>
int MyStack<T>::s_length()
{
return s_num;
}//长度
//自定义类,如果需要浅拷贝的话,拷贝构造函数可以不用写,因为编译器会自动生成;但是输出运算符<<需要重载。
//.h文件
#pragma once
#include<iostream>
using namespace std;
#include<string>
class Person
{
friend ostream& operator<<(ostream& out, Person& p)
{
out << "Name:" << p.name << "Age:" << p.age << endl;
return out;
}
public:
Person(int a=0, string n="小妖");
~Person();
private:
int age;
string name;
};
//.cpp文件
#include"Person.h"
Person::Person(int a, string n ):age(a),name(n)
{}
Person::~Person()
{
}
//main.cpp
#include"MyStack.h"
#include"Person.h"
int main(int argc,char* argv[])
{
MyStack<Person> m(5);
m.s_in(Person(1, "榕宝宝"));
m.s_in(Person(2, "榕宝宝"));
m.s_in(Person(3, "榕宝宝"));
m.s_in(Person(4, "榕宝宝"));
m.s_in(Person(5, "榕宝宝"));
m.s_in(Person(6, "榕宝宝"));
m.s_length();
m.s_traverse(true);
cout << endl;
m.s_out();
cout << endl;
m.s_traverse(false);
return 0;
}
//输出
/*
Can not add any more ingredients!
Name:榕宝宝Age:5
Name:榕宝宝Age:4
Name:榕宝宝Age:3
Name:榕宝宝Age:2
Name:榕宝宝Age:1
Name:榕宝宝Age:5
Name:榕宝宝Age:1
Name:榕宝宝Age:2
Name:榕宝宝Age:3
Name:榕宝宝Age:4
*/