顺序栈和链式栈

#include<iostream>
using namespace std;
#define ElemType int
const int MaxSize=50;
typedef struct{
    ElemType data[MaxSize];
    int top=-1;    
}SqStack; 

bool Push(SqStack &S,ElemType x){
    if(S.top==MaxSize-1)return false;
    S.data[++S.top]=x;
    return true;
}

bool Pop(SqStack &S,ElemType &x){
    if(S.top==-1)return false;
    x=S.data[S.top--];
    return true;
}
int main(){
    SqStack S;
    for(int i=1;i<=10;i++){
        Push(S,i);
    }
    int x;
    while(S.top>-1){
        Pop(S,x);
        cout<<x<<" ";
    }
    cout<<endl;
    return 0;
}
#include<iostream>
using namespace std;
#define ElemType int

typedef struct SNode{
    ElemType data;
    struct SNode *next;
}SNode;
typedef struct{
    SNode *top=NULL;
}LinkStack;

void Push(LinkStack &S,ElemType x){
    SNode *p=new SNode;
    p->data=x;
    p->next=S.top;
    S.top=p;
}

bool Pop(LinkStack &S,ElemType &x){
    if(S.top==NULL)return false;
    SNode *p=S.top;
    x=p->data;
    S.top=p->next;
    delete p;
    return true;
}

int main(){
    LinkStack S;
    for(int i=1;i<=10;i++){
        Push(S,i);
    }
    int x;
    while(S.top!=NULL){
        Pop(S,x);
        cout<<x<<" ";
    }
    cout<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lyt888/p/12562307.html