栈的操作链表+数组版

来源:互联网 发布:阿里巴巴java开发手册 编辑:程序博客网 时间:2024/05/16 12:23

数组实现

#include<cstdio>#include<cstdlib>#define MAXN 1000int 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;}



0 0
原创粉丝点击