栈 王道3.1.4 第五题

王道上面的第五题实现有问题。
例如s.satck[++s.top[0]] = x;
先进行了++s.top[0]的运算然后再在stack数组中运算。不好,自己实现。上代码。

#include <iostream>

using namespace std;

#define Elemtype int
#define Maxsize 50
typedef struct{
    Elemtype stack[Maxsize] = {0};
    int top[2] = {0,Maxsize-1};
}stk;




//入栈操作
bool push(stk &s,int i,Elemtype x)
{
    if(i<0 || i>1)
    {
        printf("栈号不对");
        exit(0);
    }
    if(s.top[1]-s.top[0] == 1)
    {
        printf("栈已满\n!");
        return 0;
    }
    switch(i)
    {
        case 0:
            s.stack[s.top[0]] = x;
            s.top[0]++;
            return 1;
            break;
        case 1:
            s.stack[s.top[1]] = x;
            s.top[1]--;
            return 1;
    }
}


//出栈
bool pop(stk &s,int i)
{
   if(i<0 || i>1)
    {
        printf("栈号不对");
        exit(0);
    }
    switch(i)
    {
        case 0:
            if(s.top[0] == -1){
                printf("栈空\n");
                return -1;
            }
            else
            {
                s.top[0]--;
                s.stack[s.top[0]] = 0;
                return 1;
            }
        case 1:
             if(s.top[1] == Maxsize){
                printf("栈空\n");
                return -1;
            }
            else
               {
                   ++s.top[1];
                   s.stack[s.top[1]] = 0;
                   return 1;
               }

    }
}



int main()
{
    stk s;
    cout<<s.top[1]<<endl;
    push(s,0,1);
    push(s,0,2);
    push(s,0,3);
    push(s,0,4);
    push(s,0,5);
    cout<<s.top[0]<<endl;
    pop(s,0);
    cout<<s.top[0]<<endl;
    for(int i = 0;i<Maxsize;i++)
        cout<<s.stack[i];
    cout<<endl;


    push(s,1,1);
    push(s,1,2);
    cout<<s.top[1]<<endl;
    for(int i = 0;i<Maxsize;i++)
        cout<<s.stack[i];
}

结果图:

猜你喜欢

转载自www.cnblogs.com/akmfwei/p/12925862.html