數據結構——用棧來判斷回文字符串
#include<iostream>
#include<string>
typedef int Status;
using namespace std;
typedef struct StackNode//定義棧
{
char data;
struct StackNode *next;
}StackNode,*LinkStack;
Status InitStack(LinkStack &S)//創建鏈棧
{
S = NULL;
return 1;
}
Status Push(LinkStack &S, char e)//入棧
{
StackNode *p;
p=new StackNode;
p->data = e;
p->next = S;
S = p;
return 1;
}
Status Pop(LinkStack &S, char &e)//出棧
{
StackNode *p;
p = new StackNode;
if (S == NULL)
return 0;
e = S->data;
p = S; S = S->next;
delete p;
return 1;
}
int main()
{
string a;
LinkStack S;//建立鏈棧
cin >> a;//輸入字符串
for (char i : a) //遍歷字符串
{
if (i != ‘ ‘)//如果字符不為空格,入棧
{
Push(S, i);
}
}
while (1)
{
char j;
for (char i : a)
{
Pop(S, j);//出棧
if (i != ‘ ‘)//如果字符不為空格,進行比較
{
if (i != j)
{
cout << "不是回文字符串" << endl;
return 0;
}
}
}
cout << "是回文字符串" << endl;
return 0;
}
}
數據結構——用棧來判斷回文字符串