顺序栈:
1 #include<iostream> 2 using namespace std; 3 const int Maxn=100; 4 typedef struct SNode{ 5 int data[Maxn]; 6 int top=-1; 7 }Stack; 8 9 int Push(Stack *s,int n){//将n个数入栈 10 if(s->top==Maxn-1) { 11 cout<<"ERROR!"; 12 return 0; 13 } 14 int v; 15 while(n!=0){ 16 s->top++; 17 cin>>v; 18 s->data[s->top]=v; 19 --n; 20 } 21 return 1; 22 } 23 int Pop(Stack *s){//出栈操作 24 if(s->top==-1){ 25 cout<<"ERROR!"; 26 return 0; 27 } 28 s->top--; 29 return 1; 30 } 31 void Print(Stack s){ 32 if(s.top==-1) cout<<"ERROR!"<<endl; 33 while(s.top>=0){ 34 cout<<s.data[s.top]<<" "; 35 --s.top; 36 } 37 cout<<endl; 38 } 39 int main(){ 40 Stack s; 41 int n; cin>>n; 42 Push(&s,n); 43 Print(s); 44 Pop(&s); 45 Print(s); 46 return 0; 47 }
链栈:
1 #include<stdlib.h> 2 #include<iostream> 3 using namespace std; 4 5 typedef struct SNode{//链栈节点结构 6 int data; 7 struct SNode *next; 8 }*SPtr; 9 typedef struct LStack{//链栈结构 10 SPtr top; 11 int count=0; 12 }Stack; 13 14 int Push(Stack *S,int n){//入栈 15 SPtr s; 16 int v; 17 while(n!=0){ 18 s=(SNode*)malloc(sizeof(SNode)); 19 cin>>v; 20 s->data=v; 21 s->next=S->top; 22 S->top=s; 23 S->count++; 24 --n; 25 } 26 return 0; 27 } 28 int Pop(Stack *S){//出栈 29 SPtr s; 30 s=S->top; 31 S->top=S->top->next; 32 S->count--; 33 free(s); 34 return 0; 35 } 36 37 void Print(Stack S){ 38 if(S.top==NULL) cout<<"ERROR!"<<endl; 39 else{ 40 SPtr s=S.top; 41 while(s!=NULL){ 42 cout<<s->data<<" "; 43 s=s->next; 44 } 45 cout<<endl; 46 } 47 } 48 int main(){ 49 Stack S; 50 int n; cin>>n; 51 Push(&S,n); 52 //Print(S); 53 Pop(&S); 54 Print(S); 55 56 return 0; 57 }