顺序栈和链式栈

#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;
}

 

上一篇:单链表


下一篇:左神算法书籍《程序员代码面试指南》——2_01在单链表和双链表中删除倒数第k个字节