所以我写了一个程序,将堆栈类实现为链表。到目前为止,该程序获取用户输入的任何字符串,并成功地将每个字符放入堆栈(至少我认为是这样)。我需要知道的是如何遍历每个字符并确定字符串是否是回文。有小费吗?
到目前为止,这是我的代码:
主要的:
#include <iostream>
#include <cstdlib>
#include <string>
#include "stack.h"
using namespace std;
int main(){
Stack o;
cout << "Enter a string" << endl;
string word;
cin >> word;
o.divide_String(word);
o.Print();
return 0;
}
标题:
#ifndef STACKS_H
#define STACKS_H
#include <string>
using namespace std;
class Stack{
private:
typedef struct item{
char letter;
item* prev;
}* itemPtr;
itemPtr stackPtr;
public:
Stack();
void Push(char letter);
void Pop();
void ReadItem(item* r);
void Print();
void Stack::divide_String(string s);
~Stack();
};
#endif
功能定义:
#include <cstdlib>
#include <iostream>
#include "stack.h"
using namespace std;
Stack::Stack(){
stackPtr = NULL;
}
Stack::~Stack(){
itemPtr p1;
itemPtr p2;
p1 = stackPtr;
while(p1 != NULL){
p2 = p1;
p1 = p1->prev;
delete p2;
}
}
void Stack::Push(char letter){
itemPtr n = new item;
n->letter = letter;
if(stackPtr == NULL){
stackPtr = n;
stackPtr->prev = NULL;
}
else{
n->prev = stackPtr;
stackPtr = n;
}
}
void Stack::Pop(){
if(stackPtr == NULL){
cout << "There is nothing on the stack." << endl;
}
else{
itemPtr p = stackPtr;
ReadItem(p);
stackPtr = stackPtr->prev;
p->prev = NULL;
delete p;
}
}
void Stack::ReadItem(item* r){
cout << r->letter;
}
void Stack::Print(){
itemPtr x = stackPtr;
cout << "Current Stack: " << endl;
while(x != NULL){
ReadItem(x);
x = x->prev;
cout << endl;
}
cout << endl;
}
void Stack::divide_String(string s){
for(char &c : s){
Push(c);
}
}