Skip to content

Instantly share code, notes, and snippets.

@tinylamb
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save tinylamb/9246034 to your computer and use it in GitHub Desktop.

Select an option

Save tinylamb/9246034 to your computer and use it in GitHub Desktop.
判断一个出栈序列能不能从1,2,3,..,n 经过栈处理后生成
/*
* =========================================================
* Filename: rails.c
* Description: 判断一个出栈序列能不能从1,2,3,..,n 经过栈处理后生成。
*
* =========================================================
*/
#include <stdio.h>
#define MAX 1010
int main(){
int n,i;//n->N i用来读入traout数列
int traout[MAX];
int stack[MAX];//没有形式化的栈
int top;//栈顶指针
while(scanf("%d",&n) && n){
//top=0; 初始化栈 wrong position
while (scanf("%d",traout) && traout[0]){//当读入的第一个数字不为0,就读入后续的n-1个数
top=0;//初始化栈
for (i=1;i<n;i++)
scanf("%d",traout+i);
int k,j=0;//k用来遍历1-N j用来遍历traout数组
for (k=1;k<=n;k++){
if(k!=traout[j])//这种情况入栈
stack[top++]=k;
else{//如果相等 pass该元素,去看看栈中是否有元素可弹出
j++;
while(top && traout[j] == stack[top-1]){
top--;
j++;
}
}
}
while (top && traout[j] == stack[top-1])//最后检查栈中元素是否可顺利弹出
top--;
printf("%s\n",(top==0)?"Yes":"No");
}
printf("\n");
}
}
@tinylamb
Copy link
Copy Markdown
Author

3 2 1 4 5

@tinylamb
Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment