栈
顺序栈
顺序栈基础代码
#include<iostream>
using namespace std;
#define MaxSize 10
#define ElemType int
typedef struct Stack{
ElemType data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &s ){
s.top=-1;
}
bool StackEmpty(SqStack &s){
if (s.top==-1){
return true;
}else{
return false;
}
}
bool Push(SqStack &s,ElemType x){
if(s.top==MaxSize-1){
return false;
}
s.data[++s.top]=x;
return true;
}
bool pop(SqStack &s,ElemType &x){
if (s.top==-1){
return false;
}
s.data[s.top--]=x;
return true;
}
int main(){
SqStack s;
InitStack(s);
}
链式栈
链式栈基础代码(无头节点)
#include<iostream>
using namespace std;
#define ElemType int
typedef struct LinkNode{
ElemType data;
struct LinkNode *next;
}LinkNode,*LinkStack;
void Init(LinkStack &s){
s=NULL;
}
bool empty(LinkStack &s){
if( s==NULL){
return true;
}else{
return false;
}
}
bool Push(LinkStack &s,ElemType x){
LinkNode *p=(LinkNode *)malloc(sizeof(LinkNode));
p->data=x;
p->next=s;
s=p;
return true;
}
bool pop(LinkStack &s){
if(empty(s)){
return false;
}
LinkNode *p;
p=s;
s=s->next;
free(p);
return true;
}
ElemType get(LinkStack &s){
if(empty(s)){
cout<<"error";
exit(0);
}
return s->data;
}
int main(){
LinkStack s;
Init(s);
Push(s,11);
cout<<get(s)<<"\n";
cout<<empty(s);
return 0;
}