顺序栈
typedef struct {
int data[MAXSIZE];
int top;//栈顶
}SqStack;
bool empty(SqStack s){
if(s.top == -1)
return true;
return false;
}
bool full(SqStack s){
if(top == MAXSIZE -1])
return true;
return false;
}
void Push(SqList &s,int x){
if(s.top == MAXSIZE - 1)
return ;//栈满
s.data[++s.top] = x;
return ;
}
void Pop(SqList &s,int &x){
if(s.top == -1)
return ;
x = s.data[s.top--];
return ;
}
链栈(带头结点)
typedef struct SNode {
int data;
struct SNode *next;
}LiStack;
bool empty(LiStack s){
if(s->next == NULL)
return true;
return false;
}
void push(LiStack &s,int x){
SNode *p = (SNode*)malloc(sizeof(LNode*));
p->data = x;
p->next = x->next;
x->next = p;
return ;
}
void Pop(LinStack &s,int &x){
if(empty(s))
return ;
SNode *p = s->next;
x = p->data;
s->next = p->next;
free(p);
return ;
}
双链表链栈,栈顶在表尾
//结点
typedef struct SNode{
int data;
struct LNode* priv;
struct LNode* next;
}
//链栈
typedef struct Stack{
struct Stack* head,rear;//表头和表尾结点
}
//初始化
void init(Stack &s){
s = (Stack*)malloc(sizeof(Stack));
SNode *p = (SNode*)malloc(sizeof(SNode));//头结点
p->next = NULL;
p->priv = NULL;
s->head = p;
s->rear = p;
return ;
}
bool empty(Stack &s){
if(s->head == s->rear)
return true;
return false;
}
void Push(Stack &s,int x){
SNode* p = (SNode*)malloc(sizeof(SNode));
p->data = x;
p->next = NULL;//表尾是栈顶,表尾插入
p->priv = s->rear;//p的前驱是曾经的尾结点
s->rear->next = p;
s->rear = p;
}
void Pop(Stack &s,int &x){
if(empty(s))
return ;
SNode *p = s->rear;
x = p->data;
s->rear = p->priv;
s->rear->next = NULL;
free(p);
}