栈(c++)
今天介绍两种在c++中写“栈”方法
1.
#include <bits/stdc++.h>
using namespace std;class mystack {
private:int a[1000];int curr = -1;
public:void push(int);void pop();int top();bool empyt();int size();
};int main()
{mystack n;while(true){int a;cout<<"1.加入元素\n2.删除元素\n3.显示顶端的元素\n4.栈是否为空(1是,0否)\n5.栈的大小\n6.结束"<<endl;cin>>a;if(a==1){int sh;cin>>sh;n.push(sh);}else if(a==2) n.pop();else if(a==3) cout<<n.top()<<endl;else if(a==4) cout<<n.empyt()<<endl;else if(a==5) cout<<n.size()<<endl;else if(a==6) break;system("pause");system("cls");}return 0;
}
void mystack::push(int v)
{if(curr<1000){a[++curr] = v;}else cout<<"栈已满\n";return;
}
void mystack::pop()
{if(curr>-1){curr--;}else cout<<"栈为空\n";return;
}
int mystack::top()
{if(curr>-1) return a[curr];else cout<<"栈为空\n";return -1;
}
bool mystack::empyt()
{if(curr==-1) return true;else return false;
}
int mystack::size()
{return curr+1;
}
2.
#include <bits/stdc++.h>
using namespace std;struct node
{int value;node* next;node* prev;node(){}node(int v){value = v;next = NULL;prev = NULL;}
};class mystack {
private:node* root = NULL;node* ptop = NULL;int n = 0;
public:void push(int);void pop();int top();bool empyt();int size();
};int main()
{mystack aaaaa;while(true){int a;cout<<"1.加入元素\n2.删除元素\n3.显示顶端的元素\n4.栈是否为空(1是,0否)\n5.栈的大小\n6.结束"<<endl;cin>>a;if(a==1){int sh;cin>>sh;aaaaa.push(sh);}else if(a==2) aaaaa.pop();else if(a==3) cout<<aaaaa.top()<<endl;else if(a==4) cout<<aaaaa.empyt()<<endl;else if(a==5) cout<<aaaaa.size()<<endl;else if(a==6) break;system("pause");system("cls");}return 0;
}
void mystack::push(int v)
{node* curr = new node(v);if(root==NULL){root = curr;ptop = curr;return;}ptop->next = curr;curr->prev = ptop;ptop = curr;n++;
}
void mystack::pop()
{if(root!=ptop){node* curr = ptop;ptop = ptop->prev;ptop->next = NULL;delete curr;n--;}else if(root==ptop&&root!=NULL){node* curr = ptop;delete curr;n--;root = NULL;ptop = NULL;}else cout<<"栈为空"<<endl;
}
int mystack::top()
{return ptop->value;
}
bool mystack::empyt()
{if(root==NULL)return true;else return false;
}
int mystack::size()
{return n;
}