编写一个程序,提示用户输入一个字符串。然后该程序把该字符串的字符逐个压入一个栈,然后从栈中弹出这些字符,并显示它们。结果显示为该字符串的逆序

/编写一个程序,提示用户输入一个字符串。然后该程序把该字符串的字符逐个压入一个栈,然后从栈中弹出这些字符,并显示它们。结果显示为该字符串的逆序/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100

typedef struct Stack
{
    char items[MAX_SIZE];
    int top;
} Stack;

void initStack(Stack *s)
{
    s->top = -1;
}
int isEmpty(Stack *s)
{
    return s->top == -1;
}
void push(Stack *s, char item)
{
    if (s->top < MAX_SIZE - 1)
    {
        s->items[++(s->top)] = item;
    }
    else
    {
        printf("栈已满,无法压入元素!\n");
    }
}
char pop(Stack *s)
{
    if (!isEmpty(s))
    {
        return s->items[(s->top)--];
    }
    else
    {
        printf("栈为空,无法弹出元素!\n");
        return '\0'; // 返回一个空字符
    }
}

int main(void)
{
    char input[MAX_SIZE];
    Stack stack;
    initStack(&stack);
    printf("请输入一个字符串: ");
    fgets(input, sizeof(input), stdin);
    input[strcspn(input, "\n")] = '\0';
    for (int i = 0; i < strlen(input); i++)
    {
        push(&stack, input[i]);
    }

    printf("逆序字符串为: ");
    while (!isEmpty(&stack))
    {
        printf("%c", pop(&stack));
    }
    printf("\n");

    return 0;
}

posted on 2024-08-10 23:23  wessf  阅读(1)  评论(0编辑  收藏  举报