栈——火车出战入站问题

来源:互联网 发布:读普通话的软件 编辑:程序博客网 时间:2024/04/28 22:03

题目:

铁路进行列车调度时,常把站台设计成栈式结构的站台。试问:      

(1)设有编号为1,2,3,4,5,6的六辆列车,顺序开入栈式结构的站台,则可能的出栈序列有多少种?      

(2)若进站的六辆列车顺序如上所述,那么是否能够得到435612, 325641, 154623和135426的出站序列,如果不能,说明为什么不能;如果能,说明如何得到(即写出"进栈"或"出栈"的序列)。


代码:

#include <stdio.h>#include<iostream>using namespace std;typedef struct{    int *stk;    int top;    int size;} stack;void initstack(stack *s, int n){    s->stk = (int*)malloc((s->size=n) * sizeof(int));    s->top = 0;}void outputstack(stack* s){    int i;int count=1;    cout<<count<<",    ";     for(i=0; i<s->top; i++)   {       cout<<s->stk[i]<<" ";   }     cout<<endl;}int stackempty(stack* s){    return !s->top;}void push(stack* s, int x){    s->stk[s->top++] = x;}int pop(stack* s){    return s->stk[--s->top];}void stackseq(stack *input, stack *s, stack *output){    if(stackempty(input) && stackempty(s))  outputstack(output);    else {        if(!stackempty(input))  {            push(s, pop(input));            stackseq(input, s, output);            push(input, pop(s));        }        if(!stackempty(s))  {            push(output, pop(s));            stackseq(input, s, output);            push(s, pop(output));        }    }}main() {    int i;    stack input, s, output;    initstack(&input, 20);    initstack(&s, 20);    initstack(&output, 20);    for(i=6; i>0; i--) push(&input, i);    stackseq(&input, &s, &output);    return 0; }

原创粉丝点击