要给学习数据结构的同学讲的题目答案(写的简单一点,好懂一点):
数据结构实验之栈:行编辑器
Problem Description
Input
Output
Example Input
whli##ilr#e(s#*s) outcha@putchar(*s=#++);
Example Output
while(*s) putchar(*s++);
#include <stdio.h>
#include <string.h>int main()
{int i;char st[300];char ch[300];while ( ~scanf( "%s", st ) ){int len = strlen(st);int top = -1;for ( i = 0; i < len; i++ ){if ( st[i] == '#' ){if ( top >= 0 )top--;}else if ( st[i] == '@' )top = -1;elsech[++top] = st[i];}for ( i = 0;i <= top; i++ ){printf ( "%c", ch[i] );}printf ( "\n" ) ;}return 0;
}
数据结构实验之栈七:出栈序列判定
Problem Description
给一个初始的入栈序列,其次序即为元素的入栈次序,栈顶元素可以随时出栈,每个元素只能入栈依次。输入一个入栈序列,后面依次输入多个序列,请判断这些序列是否为所给入栈序列合法的出栈序列。
例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个出栈序列,但4,3,5,1,2就不可能是该序列的出栈序列。假设压入栈的所有数字均不相等。
Input
第二行输入n个整数,表示栈的压入顺序。
第三行输入整数t(1<=t<=10)。
后面依次输入t行,每行n个整数,表示要判断的每一个出栈序列。
Output
Example Input
5
1 2 3 4 5
2
4 5 3 2 1
4 3 5 1 2
Example Output
yes
no
#include <stdio.h>
#include <string.h>int s[10005];
int a[10005];
int b[10005];int main()
{int n, i;int T;scanf ( "%d", &n );for ( i = 0;i < n; i++ )scanf ( "%d", &a[i] );scanf ( "%d", &T );while ( T-- ){for ( i = 0;i < n; i++ )scanf ( "%d", &b[i] );int A = 0, B = 0;int ok = 1;int top = -1;while ( B < n ){if ( a[A] == b[B] ){A++;B++;}else if ( top != -1&&s[top] == b[B] ){top--;B++;}else if ( A < n ){s[++top] = a[A];A++;}else{ok = 0;break;}}if ( ok == 1 )printf ( "yes\n" );elseprintf ( "no\n" );}return 0;
}
数据结构实验之栈八:栈的基本操作
Problem Description
堆栈是一种基本的数据结构。堆栈具有两种基本操作方式,push 和 pop。push一个值会将其压入栈顶,而 pop 则会将栈顶的值弹出。现在我们就来验证一下堆栈的使用。
Input
首先输入整数t(1 <= t <= 10),代表测试的组数,以后是 t 组输入。
对于每组测试数据,第一行输入两个正整数 m(1 <= m <= 100)、n(1 <= n <= 1000),其中m代表当前栈的最大长度,n代表本组测试下面要输入的操作数。 而后的 n 行,每行的第一个字符可能是'P’或者'O’或者'A’;如果是'P’,后面还会跟着一个整数,表示把这个数据压入堆栈;如果是'O’,表示栈顶元素出栈;如果是'A',表示询问当前栈顶的值'。
Output
对于每组测试数据,根据其中的命令字符来处理堆栈;
(1)对所有的'P'操作,如果栈满输出'F',否则完成压栈操作;
(2)对所有的'A'操作,如果栈空,则输出'E',否则输出当时栈顶的值;
(3)对所有的'O'操作,如果栈空,则输出'E',否则输出栈顶元素的值,并让其出栈;
每个输出占据一行,每组测试数据(最后一组除外)完成后,输出一个空行。
Example Input
2
5 10
A
P 9
A
P 6
P 3
P 10
P 8
A
P 2
O
2 5
P 1
P 3
O
P 5
A
Example Output
E
9
8
F
8
3
5
#include <stdio.h>
#include <string.h>int s[10005];int main()
{int n, m;int T, i;char ch[12];scanf ( "%d", &T );while ( T-- ){int top = -1;scanf ( "%d %d", &n, &m );for ( i = 0; i < m; i++ ){scanf ( "%s", ch );if ( strcmp(ch, "A") == 0 ){if ( top == -1 )printf ( "E\n" );elseprintf ( "%d\n", s[top] );}else if ( strcmp(ch, "P") == 0 ){int t;scanf ( "%d", &t );if ( top+1 == n )printf ( "F\n" );elses[++top] = t;}else if ( strcmp(ch, "O") == 0 ){if ( top == -1 )printf ( "E\n" );else{printf ( "%d\n", s[top] );top--;}}}if ( T != 0 )printf ( "\n" );}return 0;
}
代码菜鸟,如有错误,请多包涵!!!
如有帮助记得支持我一下,谢谢!!!