思路:
遍历出栈序列,对于其中任一元素k,查看当前栈是否为空,若为空或栈顶元素不等于k,则根据入栈序列进行入栈,直至入栈序列中的元素k入栈。若直至入栈序列末尾仍无k,说明出栈序列错误。入栈完成后,将k出栈。
如上述操作,直至完成出栈序列遍历,说明出栈序列正确。
代码:
- #include <stdlib.h>
- #include <stdio.h>
- struct Stack
- {
- int* base;
- int* top;
- int size;
- };
- //初始化栈
- void Init(Stack &s)
- {
- s.base = (int*)malloc(sizeof(int)*100);
- s.top = s.base;
- s.size = 100;
- }
- //入栈
- bool Push(Stack &s,int n)
- {
- if (s.top-s.base >= s.size)
- {
- s.size = s.size + 10;
- s.base = (int*)realloc(s.base,sizeof(int)*s.size);
- }
- *s.top = n;
- s.top++;
- return true;
- }
- //出栈
- bool Pop(Stack &s,int &n)
- {
- if (s.top==s.base) return false;
- s.top--;
- n = *s.top;
- return true;
- }
- bool Top(Stack &s,int &n)
- {
- if (s.top==s.base) return false;
- n = *(s.top-1);
- return true;
- }
- bool Empty(Stack s)
- {
- if (s.top == s.base) return true;
- else return false;
- }
- int main()
- {
- int i,number;
- int* input;
- int* output;
- printf("input the number of the elements:\n");
- scanf("%d",&number);
- input = (int*)malloc(sizeof(int)*number);
- output = (int*)malloc(sizeof(int)*number);
- printf("input the sequence of the elements:\n");
- for (i=0;i<number;i++) scanf("%d",&output[i]);
- for (i=0;i<number;i++) input[i] = i+1;
- Stack s;
- Init(s);
- int inIndex = 0;
- int outIndex = 0;
- //遍历出栈序列
- while (outIndex<number)
- {
- int temp;
- if (!Empty(s)) Top(s,temp);
- //若栈为空或栈顶元素不等于出栈序列中当前元素,执行入栈操作
- if (Empty(s)||temp!=output[outIndex])
- {
- while(inIndex<number&&input[inIndex]!=output[outIndex])
- {
- Push(s,input[inIndex]);
- inIndex++;
- }
- if (inIndex == number)
- {
- printf("wrong output sequece\n");
- return -1;
- }
- Push(s,input[inIndex]);
- inIndex++;
- }
- Pop(s,temp);
- if (temp!=output[outIndex])
- {
- printf("wrong output sequece\n");
- return -1;
- }
- outIndex++;
- }
- printf("rignt output sequece\n");
- return 0;
- }