C++ - Using a stack to determine if a C style string is a palindrome

余生颓废 提交于 2019-12-13 19:13:58

问题


I'm working on an assignment for class. We were provided with these three classes. (Linked here, the editor was flipping out when I tried to do them on separate lines).

We're supposed to take in a string and then use these classes to test if it's a palindrome. We can't modify said classes.

And here's my int main:

#include <iostream>
#include <cstring>
#include <cctype>
#include "stack.h"

using namespace std;

int main () {
   char testString[100];
   Stack<char> charStack;

   cout << "Please enter a string:\n> ";
   cin.getline(testString, 100);

   char caps;
   for (int i = 0; i < strlen(testString); i++) {
      if (isalpha(testString[i])) {
         caps = toupper(testString[i]);
         charStack.push(caps);
      }
   }

   for (int j = 0; j < strlen(testString); j++) {
      if (isalpha(testString[j])) {
         caps = toupper(testString[j]);
         if (charStack.firstPtr->getData() == caps) { // This part is the issue. firstPtr is private in list.h, and I can't figure out another way to compare the char array to the data in the stack
            charStack.pop(caps);
         }
      }
   }

   if (charStack.isStackEmpty()) {
      cout << endl << endl << "\"" << testString << "\"  IS a palindrome." << endl;
   }
   else {
      cout << endl << endl << "\"" << testString << "\"  is NOT a palindrome." << endl;
   }
}

As you can see, I can't quite figure out how to compare the popped data to the data in the char array. The Stack class only returns a boolean, and the pointer to the ListNode object in class List is private, so I can't use the "getData" function of that class! Anyone have any tips that could help me out?

Thanks!


回答1:


Look at function Stack::pop(STACKTYPE &data)

It takes a non-const reference argument in which it stores the element being removed (this actually happens in the implementation of List::removeFromFront(NODETYPE &value) ).

That means that you can pass a char to the pop() function and afterwards it will contain the data you're looking for.



来源:https://stackoverflow.com/questions/23255996/c-using-a-stack-to-determine-if-a-c-style-string-is-a-palindrome

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!