用c语言试设计算法判断字符串是否中心对称(利用栈作存储结构)
发布网友
发布时间:2023-07-16 16:06
我来回答
共1个回答
热心网友
时间:2024-01-18 05:30
有问题欢迎追问
2019/3/28更新
iostream已经不引用string了,string头文件需要自己引用进来。
#include <iostream>
#include <string>//2019/03/28修改
using namespace std;
class Stack
{
private:
char *top,*base,*str;
public:
Stack(int n)
{
str = new char[n+1];
base = str;
top = str;
}
Stack(string s)
{
str = new char[s.size()+1];
base = str;
top = str;
}
bool isEmpty()
{
if(top == base)
return true;
else
return false;
}
void push(char a)
{
*top = a;
top++;
}
char pop()
{
return *--top;
}
};
int main()
{
string str;
cout<<"请输入字符串:";
cin>>str;
Stack stack(str);
for(int i = 0 ; str[i] != '\0';i++)
{
if(stack.isEmpty())
stack.push(str[i]);
else
{
char temp = stack.pop();
if(temp != str[i])
{
stack.push(temp);
stack.push(str[i]);
}
}
}
if(stack.isEmpty())
cout<<"对称"<<endl;
else
cout<<"不对称"<<endl;
return 0;
}
热心网友
时间:2024-01-18 05:30
有问题欢迎追问
2019/3/28更新
iostream已经不引用string了,string头文件需要自己引用进来。
#include <iostream>
#include <string>//2019/03/28修改
using namespace std;
class Stack
{
private:
char *top,*base,*str;
public:
Stack(int n)
{
str = new char[n+1];
base = str;
top = str;
}
Stack(string s)
{
str = new char[s.size()+1];
base = str;
top = str;
}
bool isEmpty()
{
if(top == base)
return true;
else
return false;
}
void push(char a)
{
*top = a;
top++;
}
char pop()
{
return *--top;
}
};
int main()
{
string str;
cout<<"请输入字符串:";
cin>>str;
Stack stack(str);
for(int i = 0 ; str[i] != '\0';i++)
{
if(stack.isEmpty())
stack.push(str[i]);
else
{
char temp = stack.pop();
if(temp != str[i])
{
stack.push(temp);
stack.push(str[i]);
}
}
}
if(stack.isEmpty())
cout<<"对称"<<endl;
else
cout<<"不对称"<<endl;
return 0;
}