顺序栈,使用数组实现
#include<iostream>
using namespace std;
//顺序栈,C++容器适配器 push pop top empty size
class SeqStack{
public:
SeqStack(int size = 10)
:mtop(0),
mcap(size)
{
mpStack = new int[mcap];
}
~SeqStack(){
delete[]mpStack;
mpStack = nullptr;
}
public:
void push(int val){
//先判断栈满了没,满了就扩容
if(mtop==mcap){
//expand(mcap*2);
}
mpStack[mtop++]=val;
}
void pop(){
if(mtop==0){
throw "stack is empty!";
return;
}
//cout<<mpStack[mtop]<<endl;
mtop--;
}
int top() const{
if(mtop==0){
throw "stack is empty";
}
return mpStack[mtop-1];
}
bool isempty(){
if(mtop==0){
return true;
}
return false;
}
int size() const {return mtop;}
private:
void expand(int size){
int *p = new int[size];
memcpy(p,mpStack,mtop*sizeof(int));
delete [] mpStack;
mpStack = p;
mcap = size;
}
private:
int *mpStack;
int mtop; //栈顶位置
int mcap;//栈的空间大小
};
int main(){
SeqStack s;
int arr[] = {12,34,56,78,1,3,5,8};
for(int a: arr){
s.push(a);
}
while(!s.isempty()){
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
}
链式栈,使用链表的方式实现
#include<iostream>
using namespace std;
//链式栈,C++容器适配器 push pop top empty size
class LinkStack{
public:
LinkStack(){
head = new Node;
scnt = 0;
}
~LinkStack(){
Node *p = head;
while(p!=nullptr){
head = head->next;
delete p;
p = head;
}
}
public:
void push(int val){
Node *p = new Node(val);
p->next = head->next;
head->next = p;
scnt++;
}
void pop(){
if(head->next ==nullptr){
throw "Stack is empty!";
}
Node *p = head->next;
head->next = p->next;
delete p;
scnt--;
}
int top() const{
if(head->next == nullptr){
throw "Stack is empty!";
}else{
Node *p = head->next;
return p->data;
}
}
bool isempty(){
if(head->next ==nullptr){
return true;
}
return false;
}
int size() const {
int mcnt = 0;
Node *p = head->next;
while(p!=nullptr){
p=p->next;
mcnt++;
}
return mcnt;
//或者直接返回成员变量的scnt值
//return scnt;
}
private:
struct Node{
Node(int data = 0):data(data),next(nullptr){}
int data;
Node *next;
};
Node *head;
int scnt;
};
int main(){
LinkStack s;
int arr[] = {12,34,56,78,1,3,5,8};
for(int a: arr){
s.push(a);
}
cout<<s.size()<<endl;
while(!s.isempty()){
cout<<s.top()<<" ";
s.pop();
}
if(s.isempty()){
s.pop();
}
cout<<endl;
}