C语言利用栈判断字符串是否为回文

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Wofficre/article/details/78510053
#include<stdio.h>
#include<string.h>
#define OK 1
#define ERROR 0
typedef char ElemType;
typedef int Status;
typedef struct Stack1
{
	ElemType data;
	struct Stack1 *next;
}Stack1,*SqlStack1;
//初始化一个栈 
Status Init(SqlStack1 &L)
{
	L->next=NULL;
}
//进栈操作 
Status In(SqlStack1 &L,ElemType e)
{
	SqlStack1 p;
	p=new Stack1;
	p->data=e;
	p->next=L;
	L=p;
	return OK;	
}
//出栈操作 
ElemType Out(SqlStack1 &L)
{
	ElemType r;
	r=L->data;
	L=L->next;
	return r;
}
int main()
{
	SqlStack1 L;
	int s_length;
	int result=0;
	L=new Stack1;
	char s[20];
	ElemType c1,c2;
	printf("请输入想要判断的字符串:");
	scanf("%s",&s);
	s_length=strlen(s);          //取得要判断的字符串长度 
	//进栈操作 
	for(int k=1;k<=s_length/2;k++)
	{
		In(L,s[k-1]);
	}
	if(s_length%2==0)              //判断字符串长度是奇数还是偶数 
	{
		for(int i=1;i<=s_length/2;i++)
		{
			c1=Out(L);
			c2=s[s_length/2+i-1];          
			if(c1==c2)                         //进行判断 
			{
				result=1;
				continue;
			}
			else
			{
				result=0;
				break;
			}
		}
	}
	else
	{
		for(int j=1;j<=s_length/2;j++)
		{
			c1=Out(L);
			c2=s[s_length/2+j];          
			if(c1==c2)                     //进行判断
			{
				result=1;
				continue;
			}
			else
			{
				result=0;
				break;
			}
		}
	}
	//输出操作 
	if(result==1)
	{
		printf("该字符串是回文字符串!");
	}
	else
	{
		printf("该字符串不是回文字符串!");
	}
	return 0;		
}

猜你喜欢

转载自blog.csdn.net/Wofficre/article/details/78510053