【数据结构】<栈的应用>回文判断

通过栈与队列相关内容的学习,我们知道,栈是"先进后出"的线性表,而队列是"先进先出"的线性表。可以通过构造栈与队列来实现在这一算法。将要判断的字符序列依次压栈和入队。然后依次出栈和出队,通过比较出栈的字符序列与出队的字符序列是否相同来判断读入的字符序列是否为回文序列。如果全部相同则是回文序列,否则不是回文序列。

使用链式栈实现这一算法。





#include <stdio.h>
#include <stdlib.h>
#include "SStact.h"			//自定义头文件,存储链式栈的基本操作,**文件在最后自取**
/*------*/
int main(){

    char c;
    SeqStack *s;
    int i = 0;
    char ch[STACK_INIT_SIZE];
    s = (SelemType *)malloc(sizeof(SelemType));
    InitStack(s);

    while((c = getchar())!= '
')
    {
        ch[i++] = c;
        push(s,c);

    }
    int j = 0;

    while(!IsEmpty(s))
    {
        Pop(s,&c);
        if(c!=ch[j++])
        {
            printf("不是回文");
            return 0;
        }

    }
    printf("是回文");




}

"SStact.h" :

点击查看代码

#define TURE 1
#define FALSE 0
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef char SelemType;
/*---动态分配栈--*/
typedef struct
{
    SelemType *base;
    SelemType *top;
    int StackSize;
} SeqStack;
/*---初始化---*/
int InitStack(SeqStack *s)
{
    s->base = (SelemType *)malloc(STACK_INIT_SIZE*sizeof(SelemType));
    if(!s->base)
        printf("创建失败");
    else
    {
        s->top = s->base;
        s->StackSize = STACK_INIT_SIZE;
    }
}
/*---判断栈是否为空---*/
int IsEmpty(SeqStack *s)
{
    if(s->top==s->base)
    {
        return TURE;
    }
    else
    {
        return FALSE;
    }
}

/*---入栈操作---*/
int push(SeqStack *s,SelemType x)
{
    if((s->base)-(s->base)==s->StackSize)
    {
         s->base = (SelemType *)malloc(STACK_INIT_SIZE*sizeof(SelemType));
        if(s->base==NULL)
        {
            return FALSE;
        }
        s->top  =s->base+s->StackSize;
        s->StackSize +=STACKINCREMENT;
    }
    else
    {
        *s->top = x;
        s->top++;
        return(TURE);
    }
}
/*---出栈操作---*/
int Pop(SeqStack *s,SelemType *x)
{
    if(s->top==s->base)
    {
        return FALSE;
    }
    else
    {
        s->top--;
        *x = *s->top;
        return (TURE);

    }
}


原文地址:https://www.cnblogs.com/zhujiaozhu/p/15412287.html