回文字符串

利用栈来判断字符串是否回文

问题描述:
写一个算法,判断依次读入的一个以@为结束符的字母序列,是否为形如“序列1&序列2”模式的字符序列,其中序列1和序列2都不含字符&,且序列2是序列1的逆序列,如,a+b&b+a是属于该模式的序列,而 1+3&3-1则不是。

1.下面的代码是利用单栈完成的

#include"stdio.h"
#include"stdlib.h"

#define Stack_Size 50
typedef struct
{
    char   elem[Stack_Size];      
    int    top;
}SeqStack;

int init(SeqStack *S)
{
	S->top=-1;
	return 1; 
}

int Push(SeqStack *S,char x)//进栈 
{
	if(S->top==Stack_Size-1)
	return 0;
	else
	S->top++;
	S->elem[S->top]=x;
	return 1;
}

int Pop(SeqStack *S,char *x)//出栈 
{
	if(S->top==-1)
	return 0;
	*x=S->elem[S->top];
	S->top--;
	return 1;	
}
int  main()
{
	char c[200],x;
	int i=0;
	SeqStack S;
	init(&S);
	printf("请输入一行字符串:");
	gets(c);
    while(c[i]!='\0')
    {
        Push(&S,c[i]);
        i++;
	}
	for(i=0;i<=S.top;i++)
	{
		Pop(&S,&x);
		if(c[i]!=x)
		{
	        printf("此序列不是回文序列!");
	        return 0;
	    }
	}
	printf("此序列是回文序列!");
    return 0;
}

2.该代码是用双栈完成的

#include "stdio.h"
#include "stdlib.h"
#define MAX 100
#define TRUE 1
#define FALSE 0

typedef struct
{
	char array[MAX];
	int top;
}SeqStack;

void InitStack(SeqStack *S)
{
	S->top=-1;
}

int Push(SeqStack *S,char x)
{
	if(S->top==MAX-1)//栈满 
	{
		return FALSE;
	}
	else
	{
		S->top++;
	    S->array[S->top]=x;
	    return TRUE; 
	}
}
int Pop(SeqStack *S,SeqStack *N)
{    
    int i,n=S->top,m=n;
	if(S->top==-1)//栈空 
	{
		return FALSE;
	}
	else
	{
		for(i=0;i<=n;i++)
		{
			N->top++;
			N->array[N->top]=S->array[m];
			m--;
		}
	    return TRUE;
	}

}
int Compare(SeqStack *S,SeqStack *N)
{
	int i,n=S->top;
	for(i=0;i<=n;i++)
	{
		if(N->array[N->top]==S->array[S->top])
		{
			S->top--;
			N->top--;
		}
		else
		    break;
		
	}
	if(N->top>=0)
		printf("不是回文字符串\n"); 
	else
	    printf("是回文字符串\n"); 
}
int main(void)
{
	char a[100];
	int i=0;
	SeqStack S,N;
	InitStack(&S);
	InitStack(&N);

    printf("请输入一个字符串:\n");
    gets(a);
    while(a[i]!='\0')
    {
    	Push(&S,a[i]);
    	i++;
	}
	Pop(&S,&N);
	Compare(&S,&N);
	return 0;
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值