/************************************************************************/ /* 李春葆数据结构习题解析b版本三版82页,参考书上代码,有改动 */ /************************************************************************/ #include <stdio.h> #define maxsize 30 /*********************************/ /* 这里定义了一个栈以及上的操做 */ /*********************************/ struct { char data[maxsize]; int top; }st; void push(char a) { st.top++; st.data[st.top]=a; } char pop() { char temp; temp=st.data[st.top]; st.top--; return temp; } void init() { st.top=-1; } bool empty() { if (st.top==-1) return true; else return false; } int total=4;//一共四个元素 char str[]="ABCD"; int sum=0; /*************************************************************************************************/ /* m表示未进入栈的序列的标号,a[]是从栈中输出的序列的标号,curp是a[]当前的位置即便要添加的位标号 */ /*************************************************************************************************/ void process(int m,char a[],int curp) { int i; char x; if (m>total&&empty()) { for (i=0;i<curp;i++) { printf("%c",a[i]); } printf("\n"); sum++; } if (m<=total) { push(str[m-1]); process(m+1,a,curp); pop(); } if (!empty()) { x=pop(); a[curp]=x; process(m,a,curp+1); push(x); } } /*****************************************************************************/ /* 主函数,传递了1(进栈的序列标号),a[]出栈的字符数组,curp,输出的下一位置*/ /*****************************************************************************/ void main() { char a[maxsize]; init(); printf("全部出栈序列\n"); process(1,a,0); printf("总共有%d个可能\n",sum); }