火车进出站问题:有多少种出站序列

来源:互联网 发布:考研作息时间表知乎 编辑:程序博客网 时间:2024/06/11 21:03

#include <stdio.h>
#include <malloc.h> 
#include <iostream>
using namespace std;
#define STACK_SIZE 20
typedef struct

    int stack[STACK_SIZE]; 
    int top;
}SqStack;
int count=1; 
bool InitStack(SqStack &S)

    S.top=-1; 
    return true;
}
bool StackEmpty(SqStack S)

    if (S.top==-1) 
    { 
        return true; 
    }
    else  
        return false;
}  
bool ClearStack(SqStack &S)

    S.top=-1;
    return true;

int StackLength(SqStack S)
{
    return S.top+1;
}  
bool GetTop(SqStack &S,int &e)
{
    if (S.top==-1)
    {  
        return false; 
    }
    e=S.stack[S.top];
    return true;
}
bool Push(SqStack &S,int e)

    if (S.top>=STACK_SIZE-1) 
    {  
        return false; 
    } 
    S.top++;
    S.stack[S.top]=e;
    return true;
}
int Pop(SqStack &S)

    int e;
    if (S.top==-1) 
    {  
        return -1; 
    } 
    e=S.stack[S.top]; 
    S.top--;
    return e;
}  
void InOutStack(SqStack &input,SqStack &S,SqStack &output)
{
    if (StackEmpty(S)&&StackEmpty(input)) 
    { 
        int i; 
        printf("%4d     |     ",count++);  
        for (i=0;i<=output.top;i++)
        {  
            printf("%d ",output.stack[i]);  
        }  
        printf("\n"); 
    }
    else 
    {  
        if (!StackEmpty(input))  
        {   
            Push(S,Pop(input));  
            InOutStack(input,S,output);  
            Push(input,Pop(S));  
        }
        if(!StackEmpty(S))
        { 
            Push(output,Pop(S));   
            InOutStack(input,S,output);  
            Push(S,Pop(output));  
        }
    }

int main()
{
    SqStack S,input,output;
    InitStack(S); 
    InitStack(input); 
    InitStack(output); 
    int n=1; 
    printf("请输入列车数:"); 
    scanf("%d",&n);
    int i;
    for(i=n;i>0;i--)
    {  
        Push(input,i);
    } 
    printf("情况序号    出站次序情况\n"); 
    InOutStack(input,S,output);
    return 0;
}

原创粉丝点击