将单词推入堆栈并检查回文符

问题描述 投票:0回答:1

我们的老师给了我们作业,使用数据结构“堆栈”检查单词的回文。

下面是我为以下问题编写的代码:-

# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <stdbool.h>

struct Stack
{
    int top;
    int capacity;
    char *array;
};

void push(struct Stack stack, char a) //Push function.
{
    stack.array[++stack.top] = a; //Helps to push charater to a stack.
}

char pop(struct Stack stack) //Pop function.
{
    return stack.array[stack.top--]; //Helps to pop character from a stack.
}

int main(void)
{
    struct Stack original; //Original stack where the "Original" word will be pushed.
    original.top = -1;
    original.capacity = 10;
    original.array = calloc(original.capacity, sizeof(char));

    struct Stack checker; //Another stack that "Checks" whether the word is palindrome or not.
    checker.top = -1;
    checker.capacity = 10;
    checker.array = calloc(checker.capacity, sizeof(char));

    while(getchar()!='\0') //Getting all the characters from the stdin buffer and pushing it into "Original" stack.
    {
        push(original, getchar());
    }

    while(original.top != -1)
    {
        push(checker,pop(original)); //Popping from "Original" stack and pushing it to "Checker" stack.
    }

    while(checker.top != -1)
    {
        original.top = checker.top;
        if(original.array[original.top] != checker.array[checker.top]) //Checking every character in the stack if it is excatly same or not.
        {
            printf("It is not a palindrome.\n");
            return EXIT_SUCCESS;
        }
        else
        {
            checker.top = checker.top - 1;
        }
    }

    if(checker.top == -1)
    {
        printf("It is a palindrome.\n");
    }

    return 0;
}

但是无论如何我在以下行中遇到问题:-

while(getchar()!='\0') //Getting all the characters from the stdin buffer and pushing it into "Original" stack.
{
    push(original, getchar());
}

以下循环无限运行。我添加以下行的目的是,我想从stdin buffer堆栈中添加push中的各个字符,并在original堆栈中添加它,直到遇到'\0'

我在这里做错了什么?这样做是违法的吗?

附录:-

样本输入1:-公民

预期输出:-这是回文。

样本输入2:-马达马

预期输出:-它不是回文。

c while-loop stack palindrome getchar
1个回答
1
投票

此循环

while(getchar()!='\0') //Getting all the characters from the stdin buffer and pushing it into "Original" stack.
{
    push(original, getchar());
}

在任何情况下都是错误的,因为它在循环条件下和循环体内读取了两次字符。

并且您必须使用例如小键盘明确输入0。

您需要的是以下

int c;
int i = 0;

while ( i < original.capacity && ( c = getchar() ) != EOF && c != '\n' )
{
    push(original, c );
    ++i;
} 
© www.soinside.com 2019 - 2024. All rights reserved.