用栈判断输入的字符串是否是回文,将一半字符串入栈的C语言代码
时间: 2024-10-10 16:05:47 浏览: 76
在C语言中,我们可以使用栈来检查一个字符串是否是回文。以下是使用动态内存分配和标准库函数的简单实现,它会将字符串的一半字符入栈,然后对比另一半:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 100
// Stack structure
typedef struct {
char *items;
int top;
int size;
} Stack;
// Initialize the stack
void init(Stack *stack) {
stack->size = MAX_LEN;
stack->items = (char*)malloc(stack->size * sizeof(char));
stack->top = -1;
}
// Push an element onto the stack
void push(Stack *stack, char item) {
if (stack->top < stack->size - 1) {
stack->items[++stack->top] = item;
} else {
printf("Stack overflow!\n");
}
}
// Pop an element from the stack
char pop(Stack *stack) {
if (stack->top >= 0) {
return stack->items[stack->top--];
} else {
printf("Stack underflow!\n");
return '\0'; // Return null character on empty stack
}
}
// Check if a string is palindrome by comparing its halves using a stack
int is_palindrome(const char* str) {
Stack half_stack;
init(&half_stack);
int len = strlen(str);
for (int i = 0; i < len / 2; i++) {
push(&half_stack, str[i]);
}
for (int i = len / 2; i < len; i++) {
if (str[i] != pop(&half_stack)) {
return 0; // Not a palindrome
}
}
return 1; // String is a palindrome
}
int main() {
char input[] = "madam";
if (is_palindrome(input)) {
printf("%s is a palindrome.\n", input);
} else {
printf("%s is not a palindrome.\n", input);
}
return 0;
}
```
在这个代码中,我们首先初始化了一个栈,并将字符串的一半元素压入栈中。然后逐个从字符串的另一半取出元素,如果与栈顶元素不匹配,则说明不是回文。若遍历完整个字符串后栈为空,那么原字符串就是回文。
阅读全文
相关推荐
















