栈是一种操作受限的线性表。它只允许在线性表的一头插入,在另一头删除。特点就是先进先出。
按不同的存储结构,可以将栈分为顺序栈和链栈。
顺序栈的实现:
typedef int datatype;
const int MAXNUM=1000;
struct sqStack{
datatype data[MAXNUM];
int top;
//初始化
void init(){
top=-1;
}
//判断栈空
bool isEmpty(){
if(top==-1){
return true;
}
else return false;
}
//判断栈满
bool isFull(){
if(top==MAXNUM-1){
return true;
}
else return false;
}
//进栈
bool pushStack(datatype newOne){
if(isFull()){
return false;
}
else {
data[++top]=newOne;
return true;
}
}
//出栈
bool popStack(){
if(isEmpty()){
return false;
}
else {
top--;
return true;
}
}
//得到栈顶元素
datatype getTop(){
if(!isEmpty()){
return data[top];
}
}
};
共享栈:
typedef int datatype;
const int MAXSIZE=10;
struct sharedStack{
datatype data[MAXSIZE];
int top[2];
//初始化
void init(){
top[0]=-1;
top[1]=MAXSIZE;
}
//判断栈type是否为空
bool isEmpty(int type){
int temp=type==0?-1:MAXSIZE;
if(top[type]==temp){
return true;
}
else return false;;
}
//判断栈满
bool isFull(){
if(top[0]+1==top[1]){
return true;
}
else return false;
}
//栈type入栈
bool pushStack(int type,datatype newOne){
if(isFull()){
return false;
}
else {
if(type==0){
data[++top[type]]=newOne;
}
if(type==1){
data[--top[type]]=newOne;
}
return true;
}
}
//栈type出栈
bool popStack(int type){
if(isEmpty(type)){
return false;
}
else {
if(type==0){
top[type]--;
}
if(type==1){
top[type]++;
}
return true;
}
}
//得到栈type的栈顶
datatype getTop(int type){
if(!isEmpty(type)){
return data[top[type]];
}
}
};
链栈:
带头结点的链栈
typedef int datatype;
struct nodes {
datatype data;
nodes *next;
};
//带头结点的链栈
struct linkStack{
nodes *head;//头指针
//初始化
void init(){
head=(nodes*)malloc(sizeof(nodes));
head->next=NULL;
}
//判空
bool isEmpty(){
if(head->next==NULL){
return true;
}
else return false;
}
//进栈
void pushStack(datatype newOne){
nodes *temp=(nodes*)malloc(sizeof(nodes));
temp->data=newOne;
temp->next=head->next;
head->next=temp;
}
//出栈
bool popStack(){
if(isEmpty()){
return false;
}
else {
nodes *temp=head->next;
head->next=head->next->next;
free(temp);
return true;
}
}
//得到栈顶元素
datatype getTop(){
if(!isEmpty()){
return head->next->data;
}
}
};
不带头结点的链栈
typedef int datatype;
struct nodes {
datatype data;
nodes *next;
};
//不带头结点的链栈
struct linkStackII{
nodes *head;
//初始化
void init(){
head=NULL;
}
//判断栈空
bool isEmpty(){
if(head==NULL){
return true;
}
else return false;
}
//进栈
void pushStack(datatype newOne){
nodes *temp=(nodes*)malloc(sizeof(nodes));
temp->data=newOne;
temp->next=head;
head=temp;
}
//出栈
bool popStack(){
if(isEmpty()){
return false;
}
else {
nodes *temp=head;
head=head->next;
free(head);
return true;
}
}
//得到栈顶元素
datatype getTop(){
if(!isEmpty()){
return head->data;
}
}
};