闲得无聊,之前学了一波泛式编程,突发奇想用这个还原一下STL中的一些数据结构,于是就顺便手写一下栈了什么增加对它的理解:
直接上源码了,比较简单就不罗嗦了
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<stdio.h>
#include<string.h>
#include<math.h>
//#include<map>
//#include<set>
#include<deque>
#include<queue>
#include<stack>
#include<bitset>
#include<string>
#include<fstream>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
//#define max(a,b) (a)>(b)?(a):(b)
//#define min(a,b) (a)<(b)?(a):(b)
#define clean(a,b) memset(a,b,sizeof(a))// 水印
//std::ios::sync_with_stdio(false);
const int MAXN=1e5+10;
const int INF=0x3f3f3f3f;
const ll mod=1e9+7;
struct Edge{//我们要存入栈的元素,里面的东西随便改,毕竟结构体都能存了,什么int,char什么的都无所谓了
int data;
Edge(int _data=0):
data(_data){}
};
template<typename T>
class Stack{
private:
struct node{
T data;
node *nxt;
}*head,*p;
int length;
public:
Stack()
{
head=NULL;
length=0;
}
void push(T n)//入栈
{
node *q=new node;
q->data=n;
if(head==NULL)
{
q->nxt=head;
head=q;
p=q;
}
else
{
q->nxt=p;
p=q;
}
length++;
}
void pop()//出栈
{
if(length<=0)
abort();//该函数导致所有的流被关闭和冲洗
node *q;
q=p;//要删除的节点
p=p->nxt;//头节点向后移
delete(q);//删除节点
length--;
}
int size()//返回元素个数
{
return length;
}
T top()//站顶元素
{
return p->data;
}
bool Empty()
{
if(length>0)
return 0;
else
return 1;
}
void clear()
{
while(length>0)
pop();
}
};
int main()
{
//手写的阉割栈....
Stack<Edge> s;
for(int i=1;i<=10;++i)
s.push(Edge(i));
while(s.size()>2)
{
cout<<s.top().data<<" ";
s.pop();
}
cout<<endl<<s.Empty()<<endl;
s.clear();
cout<<s.Empty()<<endl;
//对比一下正常的STL中的栈
stack<Edge> st;
for(int i=1;i<=10;++i)
st.push(Edge(i));
while(st.size()>2)
{
cout<<st.top().data<<" ";
st.pop();
}
cout<<endl<<st.empty()<<endl;
while(st.size())
st.pop();
cout<<st.empty()<<endl;
}
没什么去别啊,我的输出:
感觉舒服多了,高度还原STL