C++数组栈与链表栈
数组栈
#include <iostream>
using namespace std;
class mystack{
private:int dat[1000];int curr=0;
public:void push(int);void pop();int top();bool empyt();int size();
};
void mystack::push(int b){if(curr<1000){dat[curr]=b;curr++;}
}
void mystack::pop(){if(curr>=0){curr--;}
}
int mystack::top(){if(!empyt())return dat[curr-1];else return -2147483648;
}
bool mystack::empyt(){if(curr==0){return 1;}return 0;
}
int mystack::size(){return curr;
}
int main(){mystack a;a.push(5);a.push(10);cout<<a.top()<<endl;a.pop();cout<<a.top()<<endl;cout<<a.empyt()<<endl;return 0;
}
链表栈
#include <iostream>
using namespace std;
struct node{int dat;node* next;
};
class mystack{
private:node *root=new node;node *p =root;node *curr;
public:void reset();void push(int);void pop();int top();bool empyt();int size();
};
void mystack::reset(){p->next=NULL;
}
void mystack::push(int b){p->next=new node;p->next->dat=b;p=p->next;p->next=NULL;
}
void mystack::pop(){if(p!=root){curr=p;p=root;while(p->next!=curr){p=p->next;}delete curr;p->next=NULL;}
}
int mystack::top(){if(!empyt()){curr=root;while(curr->next!=NULL){curr=curr->next;}return curr->dat;}else return -2147483648;
}
bool mystack::empyt(){if(p==root){return 1;}return 0;
}
int mystack::size(){int num=0;curr=root;while(curr->next!=NULL){curr=curr->next;num++;}return num;
}
int main(){mystack a;a.reset();a.push(5);a.push(10);cout<<a.top()<<endl;a.pop();cout<<a.top()<<endl;cout<<a.empyt()<<endl;a.pop();cout<<a.empyt()<<endl;return 0;
}