学数据结构,每个人第一次接触的恐怕都是栈,当然我也不例外。记得当年啥都不会编,只会照着书上代码抄,结果满是bug。。
今天,有了大学两年多的积淀,终于可以用自己的理解和体会来写栈的内部实现,最后也实现了一个函数模板,也就是栈内元素类型可以根据用户的输入而动态的变化。
虽然几乎每一个C++编译器中都封装了stack.h的头文件,只要包含这个头文件,就可以调用栈。实际的比赛和项目中也是这样用。但是我还是想自己实现一遍,巩固自己写到的知识,而且还可以给后来的初学者提供一个最简化的栈的版本。
#include <iostream>
using namespace std;
class stack{
public:
stack();
bool empty();
bool full();
int get_top();
void pop();
void push(int a);
public:
int data[100];
int count;
};
stack::stack(){
count = 0;
}
bool stack::empty(){
if(count == 0)
return true;
else
return false;
}
bool stack::full(){
if(count == 100)
return true;
else
return false;
}
int stack::get_top(){
if(!empty()){
return data[count-1];
}
else
return -1000; //表示出错
}
void stack::pop(){
if(!empty())
count--;
}
void stack::push(int a){
if(!full()){
data[count] = a;
count ++;
}
}
int main(){
stack s;
for(int i=0;i<5;i++){
s.push(i);
}
cout<<endl;
while(!s.empty()){
cout<<s.get_top()<<" ";
s.pop();
}
return 0;
}
#include <iostream>
using namespace std;
template <class T>
class stack{
public:
stack();
bool empty();
bool full();
T get_top();
void pop();
void push(T a);
public:
T data[100];
int count;
};
template <class T>
stack<T>::stack(){
count = 0;
}
template <class T>
bool stack<T>::empty(){
if(count == 0)
return true;
else
return false;
}
template <class T>
bool stack<T>::full(){
if(count == 100)
return true;
else
return false;
}
template <class T>
T stack<T>::get_top(){
if(!empty()){
return data[count-1];
}
else
return -1000; //表示出错
}
template <class T>
void stack<T>::pop(){
if(!empty())
count--;
}
template <class T>
void stack<T>::push(T a){
if(!full()){
data[count] = a;
count ++;
}
}
int main(){
stack<int> s;
for(int i=0;i<5;i++){
s.push(i);
}
cout<<endl;
while(!s.empty()){
cout<<s.get_top()<<" ";
s.pop();
}
//使用double类型
stack<double> s1;
s1.push(1.2);
s1.push(2.3);
s1.push(1.5);
cout<<endl;
while(!s1.empty()){
cout<<s1.get_top()<<" ";
s1.pop();
}
return 0;
}