思路:

遍历出栈序列,对于其中任一元素k,查看当前栈是否为空,若为空或栈顶元素不等于k,则根据入栈序列进行入栈,直至入栈序列中的元素k入栈。若直至入栈序列末尾仍无k,说明出栈序列错误。入栈完成后,将k出栈。

如上述操作,直至完成出栈序列遍历,说明出栈序列正确。

代码:

 
  1. #include <stdlib.h> 
  2. #include <stdio.h> 
  3.  
  4. struct Stack 
  5.     int* base; 
  6.     int* top; 
  7.     int size;    
  8. }; 
  9.  
  10. //初始化栈 
  11. void Init(Stack &s) 
  12.     s.base = (int*)malloc(sizeof(int)*100); 
  13.     s.top = s.base; 
  14.     s.size = 100; 
  15.  
  16. //入栈 
  17. bool Push(Stack &s,int n) 
  18.     if (s.top-s.base >= s.size) 
  19.     { 
  20.         s.size = s.size + 10; 
  21.         s.base = (int*)realloc(s.base,sizeof(int)*s.size); 
  22.     } 
  23.     *s.top = n; 
  24.     s.top++; 
  25.     return true
  26.  
  27. //出栈 
  28. bool Pop(Stack &s,int &n) 
  29.     if (s.top==s.base) return false
  30.     s.top--; 
  31.     n = *s.top; 
  32.     return true
  33.  
  34. bool Top(Stack &s,int &n) 
  35.     if (s.top==s.base) return false
  36.     n = *(s.top-1); 
  37.     return true
  38.  
  39. bool Empty(Stack s) 
  40.     if (s.top == s.base) return true
  41.     else return false
  42.  
  43. int main() 
  44.     int i,number; 
  45.     int* input; 
  46.     int* output; 
  47.     printf("input the number of the elements:\n"); 
  48.     scanf("%d",&number); 
  49.     input = (int*)malloc(sizeof(int)*number); 
  50.     output = (int*)malloc(sizeof(int)*number); 
  51.     printf("input the sequence of the elements:\n"); 
  52.     for (i=0;i<number;i++) scanf("%d",&output[i]); 
  53.     for (i=0;i<number;i++) input[i] = i+1; 
  54.  
  55.     Stack s; 
  56.     Init(s); 
  57.     int inIndex = 0; 
  58.     int outIndex = 0; 
  59.     //遍历出栈序列 
  60.     while (outIndex<number) 
  61.     { 
  62.         int temp; 
  63.         if (!Empty(s)) Top(s,temp); 
  64.         //若栈为空或栈顶元素不等于出栈序列中当前元素,执行入栈操作 
  65.         if (Empty(s)||temp!=output[outIndex]) 
  66.         { 
  67.             while(inIndex<number&&input[inIndex]!=output[outIndex])  
  68.             { 
  69.                 Push(s,input[inIndex]); 
  70.                 inIndex++; 
  71.             } 
  72.             if (inIndex == number)  
  73.             { 
  74.                 printf("wrong output sequece\n"); 
  75.                 return -1; 
  76.             } 
  77.             Push(s,input[inIndex]); 
  78.             inIndex++; 
  79.         } 
  80.         Pop(s,temp); 
  81.         if (temp!=output[outIndex]) 
  82.         {            
  83.             printf("wrong output sequece\n"); 
  84.             return -1; 
  85.         } 
  86.         outIndex++; 
  87.     } 
  88.     printf("rignt output sequece\n"); 
  89.     return 0;