数据结构入门系列——用栈解决实际问题(1)

一、判断回文

判断一条字符串是否为回文

bool Panduan(char *st, int n)  //n为字符串长度
{
     
	int i = 0;
	lnode *top = new lnode;
	top = InitStack();
	while (i < n)
	{
     
		Push(top, st[i++]);
	}
	i = 0; 
	//char *data=new char;//若为*,则必须初始化
	char data;
	while (!StackEmpty(top))
	{
     
		Pop(top, &data);
		if (data != st[i++])
			return 0;
		return 1;
	}
}
void main()
{
     
	cout << "please input the length of string:" << endl;
	int n;
	cin >> n;
	char *st = new char[n];
	cout << "please input the string:" << endl;
	for (int i = 0; i < n; i++)
	{
     
		cin >> st[i];
	}
	cout << "判断是否为回文数:" << endl;
	cout << Panduan(st, n);
}

二、匹配括号

用栈来实现一个表达式中的‘(’,‘[‘, ’)’, ’]’, ’{ ‘,’ }’是否匹配。

bool Match(char *st, int n)
{
     
	lnode *top;
	top = InitStack();
	int flag = 1, i = 0;
	char data;
	while (i < n&&flag)
	{
     
		switch (st[i])
		{
     
		case '(':case '[':case '{':
			top = Push(top, st[i]);
			break;
		case ')':
			if (!GetTop(top, data) || data != '(')
				flag = 0;
			top = Pop(top, &data);
			break;
		case ']':		//判断栈顶是否为'['
			if (!GetTop(top, data) || data != '[')	  //出栈操作失败或不匹配
				flag = 0;
			top = Pop(top, &data);
			break;
		case '}':		//判断栈顶是否为'{'
			if (!GetTop(top, data) || data != '{')	  //出栈操作失败或不匹配
				flag = 0;
			top = Pop(top, &data);
			break;
		default :
			break;
		}
		i++;
	}
	if (StackEmpty(top) && flag == 1)
		return 1;
	else return 0;
}
void main()
{
     
	int n;
	cout << "请输入表达式长度:";
	cin >> n;
	cout << "请输入表达式:" << endl;
	char *st = new char[n];
	for (int i = 0; i < n; i++)
		cin >> st[i];
	cout << "判断是否匹配:(“1”表示匹配,“0”表示不匹配)" << endl;
	cout << Match(st, n) << endl;
}

你可能感兴趣的:(数据结构)