栈的应用
- 任务1:编制一个满足下列要求的程序:对于输入的任意一个非负十进制数,打印输出与其等值的二进制数。
- 任务2:设计一个程序用于检测输入的符号是否匹配,如果不匹配则输出提示并退出(假设输入的符号只有小括号和中括号)。
- 任务3:设计一个算法,用于检测给定的字符串是否为对称串。
SqStack.h文件
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int top;
} SqStack;
void InitStack(SqStack *&S) {
S=(SqStack *)malloc(sizeof(SqStack));
S->top = -1;
}
int IStackEmpty(SqStack *&S) {
if (S->top == -1) {
return 1;
} else {
return 0;
}
}
void Push(SqStack *&S, int e) {
if (S->top == MAXSIZE - 1) {
printf("栈已满,无法入栈\n");
return;
}
S->data[++S->top] = e;
}
int Pop(SqStack *&S, int *e) {
if (S->top == -1) {
printf("栈为空,无法出栈\n");
return 0;
}
*e = S->data[S->top--];
return 1;
}
void DestroyStack(SqStack *&S) {
if (S != NULL) {
free(S);
S = NULL;
}
}
Main.cpp文件
#include <stdio.h>
#include "SqStack.h"
void conversion() {
SqStack *S;
int N, e;
InitStack(S);
printf("请输入十进制数N:");
scanf("%d", &N);
while (N) {
Push(S, N % 2);
N = N / 2;
}
printf("对应的二进制是:");
while (!IStackEmpty(S)) {
Pop(S, &e);
printf("%d", e);
}
printf("\n");
}
int main() {
conversion();
return 0;
}
运行结果:

CheckBrackets.cpp
#include <string.h>
#define MAXSIZE 100
#include "SqStack.h"
void CheckBrackets(char *input) {
SqStack *S;
InitStack(S);
int i = 0,e;
while (input[i] != '\0') {
if (input[i] == '(' || input[i] == '[') {
Push(S, input[i]);
} else if (input[i] == ')' || input[i] == ']') {
if (!Pop(S, &e)) {
printf("括号不匹配,请检查输入。\n");
DestroyStack(S);
break;
}
} else {
printf("无效字符:%c,请检查输入。\n", input[i]);
DestroyStack(S);
break;
}
i++;
}
if (!IStackEmpty(S)) {
printf("括号不匹配,请检查输入。\n");
DestroyStack(S);
}else
printf("括号匹配。\n");
}
int main() {
char input[100];
printf("请输入一串字符:");
scanf("%s", input);
printf("输入字符为:%s\n", input);
CheckBrackets(input);
return 0;
}
输入括号不匹配时:

输入括号匹配时:

Stack.h头文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
void push(Stack *s, char c) {
s->data[++s->top] = c;
}
char pop(Stack *s) {
return s->data[s->top--];
}
int isEmpty(Stack *s) {
return s->top == -1;
}
Main.cpp文件
#include <stdio.h>
#include "Stack.h"
// 检查字符串是否对称
int isSymmetric(char *str) {
Stack s;
initStack(&s);
int n = strlen(str);
for (int i = 0; i < n; i++) {
push(&s, str[i]);
}
for (int i = 0; i < n; i++) {
if (pop(&s) != str[i]) {
return 0;
}
}
return isEmpty(&s);
}
int main() {
char str[MAXSIZE];
printf("输入字符串:");
scanf("%s", str);
if (isSymmetric(str)) {
printf("%s是对称串。\n", str);
} else {
printf("%s不是对称串。\n", str);
}
return 0;
}
运行结果截图:


文章介绍了C++中使用栈实现的两个功能:将十进制数转换为二进制和检查输入字符中的括号是否匹配,以及检查字符串是否对称。通过SqStack结构和相应的函数展示了这些概念的运用。
172万+

被折叠的 条评论
为什么被折叠?



