• AI创作!更聪明、更完整、原创作!
  • 一款基于BingBot的超级AI机器人,问答、聊天、创作、写文案,更高效便捷的获取信息、知识和灵感!
🔥点击使用 - AI问答专业版

栈的应用回文判断和括号配对,完成程序设计,用c语言实现

时间2024-10-24 09:35:54 提问来自 山东济南市 的网友 分类AI文字 浏览93 热度0
在C语言中,可以使用栈来检查字符串是否为回文,或者检查括号是否正确配对。以下是两个简单的程序示例。 ### 1. 检查字符串是否为回文 回文是指正读和反读都相同的字符串。我们可以使用一个栈来存储字符串的前半部分,然后比较后半部分的字符是否与栈顶字符相匹配。 ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define MAX_SIZE 100 typedef struct { char data[MAX_SIZE]; int top; } Stack; void initStack(Stack *s) { s->top = -1; } bool isEmpty(Stack *s) { return s->top == -1; } bool push(Stack *s, char c) { if (s->top == MAX_SIZE - 1) { return false; } s->data[++(s->top)] = c; return true; } bool pop(Stack *s, char *c) { if (isEmpty(s)) { return false; } *c = s->data[(s->top)--]; return true; } bool isPalindrome(char *str) { Stack s; initStack(&s); int len = strlen(str); for (int i = 0; i < len / 2; i++) { push(&s, str[i]); } for (int i = len / 2; i < len; i++) { char temp; pop(&s, &temp); if (str[i] != temp) { return false; } } return true; } int main() { char str[MAX_SIZE]; printf("Enter a string: "); scanf("%s", str); if (isPalindrome(str)) { printf("The string is a palindrome.\n"); } else { printf("The string is not a palindrome.\n"); } return 0; } ``` ### 2. 检查括号是否正确配对 我们可以使用一个栈来存储遇到的开括号,并在遇到闭括号时检查栈顶的开括号是否与之匹配。 ```c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAX_SIZE 100 typedef struct { char data[MAX_SIZE]; int top; } Stack; void initStack(Stack *s) { s->top = -1; } bool isEmpty(Stack *s) { return s->top == -1; } bool push(Stack *s, char c) { if (s->top == MAX_SIZE - 1) { return false; } s->data[++(s->top)] = c; return true; } bool pop(Stack *s, char *c) { if (isEmpty(s)) { return false; } *c = s->data[(s->top)--]; return true; } bool isValidParentheses(char *str) { Stack s; initStack(&s); for (int i = 0; str[i] != '\0'; i++) { char c = str[i]; switch (c) { case '(': case '{': case '[': push(&s, c); break; case ')': if (!pop(&s, &c) || c != '(') return false; break; case '}': if (!pop(&s, &c) || c != '{') return false; break; case ']': if (!pop(&s, &c) || c != '[') return false; break; } } return isEmpty(&s); } int main() { char str[MAX_SIZE]; printf("Enter an expression with parentheses: "); scanf("%s", str); if (isValidParentheses(str)) { printf("The parentheses are correctly matched.\n"); } else { printf("The parentheses are not correctly matched.\n"); } return 0; } ``` 这两个程序分别实现了使用栈来判断字符串是否为回文和括号是否正确配对的功能。你可以将这些代码复制到你的C语言开发环境中,编译并运行它们。

内容创作(普通版)

内容创作(高级版)

AI智能问答网 免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用创作工场,更聪明、更完整、更原创!

上一篇 题目:假设有三个整数m、n和p,满足m+n=20,1/m + 1/n=5/24,且p=m*n。请问p的取值是多少? (A) 72 (B) 36 (C) 48 (D) 96 (E) 24 下一篇 运用修辞手法写T恤相关文案