出棧入棧合法性檢驗,C/C++語言程式
“棧.h” #include<stdio.h> #include<stdlib.h>
#define A 40 typedef int Datatype;
typedef struct Stack{ Datatype stack_array[A]; int top; int bottom; }Stack;
//棧的初始化 Stack InitStack() { Stack S; S.bottom = S.top = 0; return S; } //壓棧 int PushS(Stack* S, Datatype e) { (*S).stack_array[(*S).top] = e; (*S).top++; return 0; }
//出棧 Datatype* PopS(Stack S) { if (S.top == 0) return NULL; S.top--; }
void test() { int in[] = { 1, 2, 3, 4, 5 }; int out[] = { 1,2,5,3,4 }; Stack S=InitStack(); int size = sizeof(in) / sizeof(int); int ii = 0; int io = 0; printf("\n輸入:"); for (ii = 0; ii < size; ii++) printf("%d ", in[ii]); printf("\n輸出: "); for (io = 0; io < size; io++) printf("%d ", out[io]); printf("\n"); ii = 0; io = 0;
while (ii <size) { if (in[ii] == out[io]) { ii++; io++; } else { PushS(&S, in[ii]); ii++;
} }
while (io<size) { S.top--; if (out[io] == S.stack_array[S.top]) { PopS(S); io++; } else { printf("非法!\n"); return ; } } printf("合法\n");
}
“源.cpp” #include"棧.h" #include<Windows.h>
int main() { test(); system("pause"); return 0; }