#include <iostream>
using namespace std;
/**
栈 后进先出
1, 初始化栈initstack
2,入栈push()
3,出栈pop
4,显示所有栈元素
*/
#define MaxSize 100
typedef char ElemType;
typedef struct {
ElemType stack[MaxSize];
int top;
} stacktype;
void initstack(stacktype *S){
S->top=-1;
}
void push(stacktype *S , ElemType x){
if(S->top > MaxSize){
cout<<"栈溢出"<<endl;
}else{
S->top++;
S->stack[S->top]=x;
}
}
void pop(stacktype *S){
if(S->top==-1){
cout<<"栈溢出"<<endl;
}else{
S->top--;
}
}
void display(stacktype *S){
int i;
cout<<"栈中的元素:"<<endl;
for(i=S->top;i>=0;i--){
printf("%C",S->stack[i]);
}
}
void main(){
struct stacktype *st;
initstack(st);
cout<<"依次插入a,b,c,d"<<endl;
push(st,'a');
push(st,'b');
push(st,'d');
push(st,'d');
display(st);
pop(st);
display(st);
pop(st);
display(st);
pop(st);
display(st);
}
#include <iostream>
#include <malloc.h>
using namespace std;
/**
栈 链表
1, 初始化栈initstack
2,入栈push()
3,出栈pop
4,显示所有栈元素
*/
#define MaxSize 100
typedef char ElemType;
typedef struct linknode{
ElemType data;
struct linknode *next;
} linkStack;
void initstack(linkStack **S){
S=NULL;
}
void push(linkStack **S , ElemType x){
linkStack *q;
q=(linkStack *)malloc(sizeof(linkStack));
q->data=x;
q->next=*S;
*S=q;
}
void pop(linkStack **S){
linkStack *t;
if(*S==NULL){
cout<<"栈溢出"<<endl;
}else{
t=*S;
*S=t->next;
free(t);
}
}
void display(linkStack **S){
linkStack *q;
q=*S;
cout<<"栈中的元素:"<<endl;
while(q != NULL){
printf("%C",q->data);
q=q->next;
}
}
void main(){
linkStack *stack;
initstack(&stack);
cout<<"依次插入a,b,c,d"<<endl;
push(&stack,'a');
push(&stack,'b');
push(&stack,'c');
push(&stack,'d');
display(&stack);
cout<<"出栈"<<endl;
pop(&stack);
display(&stack);
cout<<"出栈"<<endl;
pop(&stack);
display(&stack);
cout<<"出栈"<<endl;
pop(&stack);
display(&stack);
}