双栈转置序列

试设计一个双栈结构,它有两个端点 end1 和 end2,满足从 end1 端插入的表目只能从 end1 端被删除,从 end2 端插入的表目只能从 end2 端被删除,并给出指定端 i(i=1,2)的进栈 push(S,e,i)和出栈 pop(S,e,i)操作的算法描述。再设计一个算法,它能够将一个有限长度的数据 序列 a1,a2,...,an,按照下标奇偶序号交替的方式将 ai (1≤i≤n)分别从两端入栈,然后将 数据出栈以实现整个数据序列的倒排。

#include <iostream>
#include <stack>
#include <string>
using namespace std;

#define max 1024
typedef struct {
    int base[max];
    int *top[3]={nullptr, base, base+max-1};
}DSqStack;

int push(DSqStack &S, int e, int i){
    if(S.top[2]-S.top[1]==1)
        return 0;
    if(i==1)
        *S.top[1]++=e;
    else if(i==2)
        *S.top[2]--=e;
    else
        return 0;
    return 1;
}

int pop(DSqStack &S, int &e, int i){
    if(i==1){
        if(S.top[1]==S.base)
            return 0;
        e=*--S.top[1];
        return 1;
    }
    else if(i==2){
        if(S.top[2]==S.base+max-1)
            return 0;
        e=*++S.top[2];
        return 1;
    }
    else
        return 0;
}

int Reverse(DSqStack S, int arr[], int n){
    int j;
    for (j=1;j<=n;j++)
        if (j%2==0) push(S, arr[j-1],2);
        else push(S, arr[j-1],1);
    for (j--;j>=1;j--)
        if (j%2==0) pop(S, arr[n-j],2);
        else pop(S, arr[n-j],1);
    return 1;
}

int main(){
    int arr[max];
    int n;
    while(cin>>n){
        cout<<"Input the arr"<<endl;
        for(int i=0;i<n;i++)
            cin>>arr[i];
         DSqStack S;
        Reverse(S,arr, n);
        cout<<"Reverse complete"<<endl;
        for(int i=0;i<n;i++)
            cout<<arr[i];
    }
    return 0;
}
原文地址:https://www.cnblogs.com/DaiShuSs/p/11508363.html