【问题标题】:C++ - Using a stack to determine if a C style string is a palindromeC++ - 使用堆栈来确定 C 风格的字符串是否是回文
【发布时间】:2014-06-08 23:26:27
【问题描述】:

我正在做一项课堂作业。我们得到了thesethreeclasses。 (链接在这里,当我试图在不同的行上执行它们时,编辑器正在翻转)。

我们应该接受一个字符串,然后使用这些类来测试它是否是回文。我们不能修改这些类。

这是我的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;
   }
}

如您所见,我不太清楚如何将弹出的数据与 char 数组中的数据进行比较。 Stack类只返回一个布尔值,而List类中指向ListNode对象的指针是私有的,所以我不能使用那个类的“getData”函数!任何人有任何提示可以帮助我吗?

谢谢!

【问题讨论】:

  • 回文很容易。为什么要为他们使用课程?
  • 这就是任务。我们的教授知道,用其他方式做起来会容易得多。
  • 你在开玩笑吗,在“这三个类”中有三个链接!???
  • @indiv: 等等,弹出后如何比较?编辑:实际上,只是想通了!没有注意到“值”是通过引用传入的。所以我可以传入一个空白测试字符,然后将其与 c 字符串进行比较!谢谢!
  • 请告诉您的教授List 缺少复制构造函数which is bad。

标签: c++ stack


【解决方案1】:

看函数Stack::pop(STACKTYPE &amp;data)

它接受一个非常量引用参数,其中存储要删除的元素(这实际上发生在 List::removeFromFront(NODETYPE &amp;value) 的实现中)。

这意味着您可以将char 传递给pop() 函数,然后它将包含您要查找的数据。

【讨论】:

    猜你喜欢
    • 2021-12-08
    • 2013-07-26
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2012-04-02
    • 2011-02-14
    相关资源
    最近更新 更多