/************************************************************************/ /* 李春葆數據結構習題解析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); }