1. 程式人生 > >判斷給定字串是否迴文(棧和佇列)

判斷給定字串是否迴文(棧和佇列)

若一個字串的正序與倒序相同,則稱其為迴文字串。

程式碼如下:

#define m 100 
typedef struct zhan         //定義棧
 { 
  char data[m]; 
  int  top; 
}zhan;  

typedef struct dui{          //定義佇列
 char data[m]; 
 int  front; 
 int  rear; 
}dui;  

 

# include "StructDefine.h"

void cshz(zhan *s);     //初始化棧

int pdzk(zhan *s) ;       //判斷棧是否為空

void ruzhan(zhan *s,char x);  //入棧

char chuzhan(zhan *s)  ;      //出棧

 void cshdl(dui *q);      //初始化佇列

 void rudui(dui *q,char e);     //入隊

 char chudui(dui *q) ;        //出隊

 void panduan(zhan *s,dui *q);      //判斷

 

# include <iostream>
# include "StructDefine.h"
# include <malloc.h>
using namespace std;

void cshz(zhan *s)      //初始化棧

  s->top=0; 
}                         
 
int pdzk(zhan *s)        //判斷棧是否為空

  if(s->top==0)                         
  { 
    return 0; 
  } 
  else 
  { 
    return 1; 
  }              
}                        
 
void ruzhan(zhan *s,char x)  //入棧

  if(s->top==m)                       
   { 
     printf("棧空\n"); 
  }                         
  else                                   
   {               
     s->data[++s->top]=x;                
   } 
}                       
 
char chuzhan(zhan *s)        //出棧

  char y; 
  if(s->top==0)                         
  
  { 
    printf("棧空\n");    
    return '0';   
  }
  else                                 
  {     
    y=s->data[s->top];                   
    s->top=s->top-1;                       
    return y; 
  } 
}                   

 void cshdl(dui *q)      //初始化佇列

  q->front=q->rear=0;                            
}                          
 
void rudui(dui *q,char e)            //入隊
{
  if((q->rear+1)%m==q->front)           
   { 
    printf("佇列為空\n"); 
   } 
   else 
   { 
    q->data[q->rear]=e;                
    q->rear=(q->rear+1);             
   } 
}                     
 
char chudui(dui *q)         //出隊

  char f; 
  if(q->front==q->rear)                 
   { 
     printf("佇列為空\n");    
     return 0; 
   } 
   else 
   { 
     f=q->data[q->front];   
     q->front=(q->front+1);            
     return f; 
   } 
}  

void panduan(zhan *s,dui *q){
     int y=0; 
  while(pdzk(s))          
   { 
     if(chuzhan(s)==chudui(q)) 
     { 
      y=1;                 
      continue;            
     } 
     else                   
     { 
      y=0; 
      break;                 
     } 
   } 
   if(y==1) 
    printf("此字串為迴文\n"); 
  else 
    printf("此字串不是迴文\n");
}

 

#include "huiwen.h"
# include <iostream>
using namespace std;

int  main()             
{                                 
  char c; 
  zhan *s=(zhan *)malloc(sizeof(zhan)); 
  dui *q=(dui *)malloc(sizeof(dui)); 
  cshz(s);   
  cshdl(q); 
  printf("輸入一個字串:\n");
  while((c=getchar())!='#') 
  {
    ruzhan(s,c);            
    rudui(q,c); 
  } 
    panduan(s,q);
   system("pause");
  return 0;
}

 

小結:抓住迴文字串的特點即可。