通過棧與隊列相關內容的學習,我們知道,棧是"先進后出"的線性表,而隊列是"先進先出"的線性表。可以通過構造棧與隊列來實現在這一算法。將要判斷的字符序列依次壓棧和入隊。然后依次出棧和出隊,通過比較出棧的字符序列與出隊的字符序列是否相同來判斷讀入的字符序列是否為回文序列。如果全部相同則是回文序列,否則不是回文序列。
使用鏈式棧實現這一算法。
#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())!= '\n')
{
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);
}
}