题目如下:(共三小题)
题目一:
栈的应用
(1)回文判断:给定一个字符串,判断其是否为回文。
代码:
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
char a[1024];
int i, j;
gets(a); //从键盘中输出字符
j = strlen(a) - 1; //将字符串的长度-1之后赋值给j
for (i = 0; i < j; i++, j--) //将字符从两侧开始逐渐对比是否相同
if (a[i] != a[j]) break; //不同则跳出循环
if (a[i] == a[j])
printf("该字符串是回文字符\n"); //若相同则输出
else printf("该字符串不是回文字符\n"); //若不相同则输出
return 0;
}
运行截图:
(2)设一个栈的输入序列为1,2,…,n,编写算法,判断一个给定的序列p1,p2,…,pn是否是一个合理的输出序列(pi为1~n的整数)。
代码:
#include <stdio.h>
#define size 50
typedef struct {
int elem[size];
int top;
} SepStack,*Sep;
void Init(Sep S) {
S->top = -1;
}
void Push(Sep S,int e) {
S->top++;
S->elem[S->top] = e;
}
int Pop(Sep S) {
int e = S->elem[S->top];
S->top--;
return e;
}
void PrintStack(SepStack S) {
while(S.top>-1) {
printf("%d ",S.elem[S.top--]);
}
}
int main() {
SepStack S;
Init(&S);
int i,c=0,args[size];
puts("输入入栈顺序(以999结束):");
for(i =0;; i++) {
scanf("%d",&args[i]);
if(args[i]==999)
break;
c++;
}
for(i=0; i<c; i++) {
Push(&S,args[i]);
}
puts("出栈顺序(以999结束): ");
int arr[size];
c=0;
for(i =0;; i++) {
scanf("%d",&arr[i]);
if(arr[i]==999)
break;
c++;
}
puts("正确出栈顺序:");
PrintStack(S);
int jud=0;
for(int i=0; i<c; i++) {
int e=Pop(&S);
if(arr[i]!=e) {
jud++;
}
}
puts(" ");
if(jud==0)
puts("因此输出合理");
else
puts("因此输出不合理");
}
运行截图:
题目二:
递归与回溯:八皇后问题。
代码:
#include<stdio.h>
#include<stdlib.h>
#define N 10
char arr[N][N];
struct Pos
{
int xpos; //列偏移量
int ypos; //行偏移量
}p[3] = { { -1, -1 }, { 0 ,-1 }, {1,-1 } };
//初始化数组
void Init()
{
int i = 0;
for (i = 0; i < N; i++)
{
int j = 0;
for (j = 0; j < N; j++)
{
arr[i][j] = ' ';
//边框设置为#
arr[0][j] = '#';
arr[N - 1][j] = '#';
arr[i][0] = '#';
arr[i][N - 1] = '#';
}
}
}
//展示数组
void Show()
{
int i = 0;
for (i = 0; i < N; i++)
{
int j = 0;
for (j = 0; j < N; j++)
{
printf("%c ", arr[i][j]);
}
printf("\n");
}
}
//检查是否可以摆放
int check_put( int row, int col)
{
int i;
int ret = 1;
int nr = row;
int nc = col;
for (i = 0; ret&&i < 3; i++)
{
nr = row;
nc = col;
while ((arr[nr][nc] != '#')&&ret)
{
if (arr[nr][nc] == ' ')
{
nr = nr + p[i].ypos;
nc = nc + p[i].xpos;
}
else
ret = 0;
}
}
return ret;
}
//摆皇后
void Find(int row)
{
int j = 0;
static int count = 0;
if (row > N - 2)
{
Show();
count++;
printf("count=%d\n", count);
}
else
{
for (j = 1; j < N - 1; j++)
{
if (check_put(row, j))
{
arr[row][j] = '*';
Find( row + 1);
arr[row][j] = ' ';
}
}
}
}
int main()
{
Init();
Find(1);
system("pause");
return 0;
}
运行截图: