数组实现

 

#include<cstdio>
#include<cstdlib>
#define MAXN 1000
int isEmpty(const int top){
    return !(top+1);
}
void pop(int *s,int *top){
    s[(*top)--]=0;
}
void push(int *s,int *top){
    int x;
    scanf("%d",&x);
    s[++*top]=x;
}
void showStack(int *s,int top){
    int i;
    for(i=0;i<top+1;i++){
        if(i==0){
            printf("%d",s[i]);
        }
        else{
            printf(" %d",s[i]);
        }
    }
    puts("");
}
int main(){
    int *s=(int *)malloc(MAXN*sizeof(int)),top=-1;
    char str[20];
    while(~scanf("%s",str)){
        if(str[1]=='o'||str[1]=='O'){
            if(!isEmpty(top)){
                pop(s,&top);
            }
            else{
                puts("Empty");
            }
        }
        else if(str[1]=='u'||str[1]=='U'){
            push(s,&top);
        }
        showStack(s,top);
    }
    return 0;
}

链表实现

 

 

/**
c++链表栈
push,pop,showStack,isEmpty;
*/
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<stack>
#include<iostream>
using namespace std;
typedef struct node{
    int data;
    struct node *next;
}NODE;
NODE* push(NODE *top,int x){
    NODE *tmp=(NODE*)malloc(sizeof(NODE));
    tmp->data=x;
    tmp->next=NULL;
    if(!top){
        top=tmp;
        top->next=NULL;
    }
    else{
        tmp->next=top;
        top=tmp;
    }
    return top;
}
NODE* pop(NODE *top){
    NODE *tmp=top;
    top=top->next;
    free(tmp);
    return top;
}
void showStack(NODE*top){
    NODE *p=top;
    while(p){
        if(p->next){
            printf("%d ",p->data);
        }
        else{
            printf("%d\n",p->data);
        }
        p=p->next;
    }
}
bool isEmpty(NODE *s){
    bool ret;
    if(s){
        ret=false;
    }
    else{
        ret=true;
    }
    return ret;
}
int main(){
    int x;
    char str[10];
    NODE *s=NULL;
    while(~scanf("%s",str)){
        if(str[1]=='o'||str[1]=='O'){///pop
            if(!isEmpty(s)){
                s=pop(s);
            }
            else{
                puts("empty");
            }
        }
        else if(str[1]=='u'||str[1]=='U'){///push
            scanf("%d",&x);
            s=push(s,x);
        }
        showStack(s);
    }
    return 0;
}