C/C++_输入一个字符串判断是否是回文

#include 

#include 

using namespace std;

#define MAX 100

typedef int Ofstack;

typedef char selem;

typedef struct {

	selem* base;

	selem* top;

	int stacksize;

}SqStack;
//初始化
Ofstack FristStack(SqStack& S)

{

	S.base = new selem[MAX];

	if (!S.base) return -1;

	S.top = S.base;

	S.stacksize = MAX;

	return 1;

}
//入栈
Ofstack PushStack(SqStack& S, selem x)

{

	if (S.top - S.base == S.stacksize)

		return 0;

	*S.top++ = x;

	return 1;

}
//出栈
Ofstack PopStack(SqStack& S, selem& x)

{

	if (S.top == S.base)	return 0;

	x = *--S.top;

	return 1;

}

bool StackEmpty(SqStack x)
{

	if (x.top != x.base)

		return true;

	else

		return false;

}

int Compare(char* x)//将一半字符入栈,再弹出字符比较,

//int Compare(char x[]) 	//注意字符序列长度的奇偶性 

{
	int flag = 0;

	SqStack s;

	selem e, temp;

	FristStack(s);

	int i, n;

	n = strlen(x);//n为输入字符串的长度

	for (i = 0; i < n / 2; i++)//将前一半字符入栈 

	{

		PushStack(s, x[i]);

	}

	for (i = (n % 2 == 0 ? n / 2 : (n + 1) / 2); i < n; i++)//判断n的奇偶性, 字符后面的一半

	{

		PopStack(s, e);

		temp = e;

		if (temp == x[i])//判断出栈的元素是否和栈外另一半相同

			flag = 1;

		else

		{

			flag = 0;

			break;

		}

	}

	return flag;

}

int main()

{

	cout << "请输入长度小于或者等于100的字符序列:\n";

	char stackTow[MAX];

	cin >> stackTow;

	if (Compare(stackTow))

		cout << "此序列是回文数!\n";

	else

		cout << "此序列不是回文数!\n";

	return 0;

}

你可能感兴趣的:(c/c++)