1. 程式人生 > >資料結構簡明教程李春葆5版 示例題目 迴文 匹配{}[]() 轉換二進位制

資料結構簡明教程李春葆5版 示例題目 迴文 匹配{}[]() 轉換二進位制

#include"iostream"


using namespace std;


#define MaxSize 100


typedef char ElemType;


typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;


void InitStack(SqStack &st){
st.top=-1;
}


void DestroyStack(SqStack st){

}


int Push(SqStack &st,ElemType x){
if(st.top==MaxSize-1)
return 0;
else{
st.top++;
st.data[st.top]=x;
return 1;
}
}


int Pop(SqStack &st,ElemType &x){
if(st.top==-1) return 0;
else{
x=st.data[st.top];
st.top--;
return 1;
}
}


int GetTop(SqStack st,ElemType &x){
if(st.top==-1)
return 0;
else{
x=st.data[st.top];

return 1;
}
}


int StackEmpty(SqStack st){
if(st.top==-1) return 1;
else return 0;
}




int ishw(char str[]){
SqStack st;
InitStack(st);
int i=0;char ch;
while((ch=str[i++])!='\0')
Push(st,ch);
i=0;
while(!StackEmpty(st)){
Pop(st,ch);
if(ch!=str[i++]){
DestroyStack(st);
return 0;
}
}
DestroyStack(st);
return 1;
}




int match(char *exps){
char st[MaxSize];
int nomatch=1,top=-1,i=0;
while(exps[i]!='\0'&&nomatch==1){
switch(exps[i]){
case'(':case'[':case'{':
top++;st[top]=exps[i];break;
case')':if(st[top]=='(') top--;
else nomatch=0;
break;
case']':if(st[top]=='[') top--;
else nomatch=0;break;
case'}':if(st[top]=='{') top--;
else nomatch=0;break;
default:break;
}
i++;


}
if(nomatch==1&&top==-1) return 1;
else return 0;
}




void trans(int d,char b[]){
char st[MaxSize],ch;
int i=0,top=-1;
while(d!=0){
ch='0'+d%2;
top++;st[top]=ch;
d/=2;
}
while(top!=-1){
b[i]=st[top];top--;
i++;
}
b[i]='\0';
}




void main(){
char ch[]="asdasd";
char ch1[]="zxccxz";
if(ishw(ch)){
cout<<ch<<"   是迴文\n";
}else{
cout<<ch<<"   不是迴文\n";

}


if(ishw(ch1)){
cout<<ch1<<"   是迴文\n";
}else{
cout<<ch1<<"   不是迴文\n";

}


char ch2[]="[(as{d)ff}ff]";
char ch3[]="[fgf{fjh}g]";


if(match(ch2)){
cout<<ch2<<"    匹配\n";
}else{
cout<<ch2<<"    不匹配\n";

}

if(match(ch3)){
cout<<ch3<<"    匹配\n";
}else{
cout<<ch3<<"    不匹配\n";

}


int d;
char ch4[MaxSize];
while(d<0){
cout<<"輸入一個正整數\t";
cin>>d;


}
trans(d,ch4);
cout<<"對應的二進位制"<<ch4<<endl;
}