弹出堆栈字符并将它们保存到字符串的问题

Issue with popping stack characters and saving them to a string

我有时在编程方面遇到一些麻烦,但我通常都很好并且总是无法完全理解概念,但是当我尝试实现一个实际的程序来执行操作时我碰壁了.

我有一个作业要完成,我必须接受一个输入字符串,逐个字符地将其读入堆栈(使用链表),然后将结果从堆栈中弹出,将其存储到新字符串,然后比较字符串以确定该特定输入字符串是否为回文。

到目前为止,我似乎 运行 遇到的唯一问题是(希望如此)在程序的最后。当我尝试从堆栈中弹出每个字符并将它们单独存储在一个字符串中时,我遇到一个问题,其中 Visual Studio 告诉我:“error C2664: 'Stack::pop' : cannot convert parameter 1从 'unsigned int' 到 'char &'"

    void Stack::pop(char  &input_string) {
    StackNode* temp;

    if (isEmpty()) {
        cout << "The stack is empty." << endl;
    }

    else {
        input_string = top->value;
        temp = top->next;
        delete top;
        top = temp;
    }
}

    int main () {

    Stack stringStack;

    string input_string;
    string reverse_input;

    cout << "Input the desired string to determine if it is a palindrome or not.  No spaces please." << endl;

    cin >> input_string;

    for (unsigned int i=0; i < input_string.length(); i++) {
        stringStack.push(input_string[i]);
    }

    while (!stringStack.isEmpty()) {
        for (unsigned int j=0; j < input_string.length(); j++) {
            stringStack.pop(j) = reverse_input[j];
        }
    }

    if (reverse_input == input_string) {
        cout << "Your input is a palindrome!" << endl;
    }
    else {
        cout << "Your input was not a palindrome, try again!" << endl;
    }

    system ("PAUSE");
}

我意识到它告诉我不能将 j 传递给 pop 函数来弹出值,因为我声明的 pop 函数需要一个 char 值。

是否可以通过将 pop 函数的输入更改为整数,然后使用 pop 函数 return char 值来解决这个问题?

除了 pop 函数和主要执行函数之外,我排除了 cpp 文件的所有其他函数,如果您出于某种原因需要查看其他部分,请告诉我。

在此先感谢您的帮助。非常感谢。

本部分:

while (!stringStack.isEmpty()) {
    for (unsigned int j=0; j < input_string.length(); j++) {
        stringStack.pop(j) = reverse_input[j];
    }
}

假设目标是使用 pop 获取堆栈顶部的元素并将其添加到字符串 reverse_input 的末尾,这样得到的 reverse_input 将与input_string相反,循环太多了。

for( unsigned int j = 0; !stringStack.isEmpty() ; j++ ){
    //Code Here
}

或:

while( !stringStack.isEmpty() ){
    //Code Here
}

另外 stringStack.pop(j) = reverse_input[j]; 实际上并没有分配任何东西,因为 pop 是一个空函数。

另一种选择如下:

修改 pop 使其 returns 位于顶部的 char 元素。

char Stack::pop() {
    StackNode* temp;
    char mychar = '[=13=]';

    if (isEmpty()) {
        cout << "The stack is empty." << endl;
    }

    else {
        mychar = top->value;
        temp = top->next;
        delete top;
        top = temp;
    }
    return mychar;
}

然后:

reverse_input = ""; //To make sure it is empty
while( !stringStack.isEmpty() ){
    reverse_input += stringStack.pop();
}