1 如果有结束符的时候,用char
//判断的时候有结束符
//就单个字符 char判断
#include<bits/stdc++.h>
#include<ctype.h>
using namespace std;
#define Maxsize 100
typedef struct Stack{
int data[Maxsize];//0~Maxsize-1
int top;
}Stack,*pStack;
pStack CreateStack(){
pStack head=new Stack();
head->top=-1;
return head;
}
bool isFull(pStack L){
if(L->top ==Maxsize-1) return true;
return false;
}
bool isEmpty(pStack L){
if(L->top ==-1) return true;
return false;
}
bool Push(pStack L,char e){
if(isFull(L)) return false;
L->data [++(L->top)]=e;
return true;
}
char Pop(pStack L){
if(isEmpty(L)) return false;
return L->data [(L->top )--];
}
int main(){
pStack head;
head=CreateStack();
char str[50];char c,e;
cin>>c;
bool isfirst=true;
bool ismatch=true;
while(c!='#'){
while(isdigit(c)||c=='.'){
if(isfirst) cout<<c;
else if(!ismatch) cout<<" "<<c;
else if(ismatch) cout<<c;
cin>>c;
if(!isdigit(c)&&c!='.'){
ismatch=false;
isfirst=false;
break;
}
isfirst=false;
ismatch=true;
}
if(c==')'){
e=Pop(head);
while(e!='('){
cout<<" "<<e;
e=Pop(head);
}
}
//如果是+-的话,就把栈顶元素 1弹出判断优先级 2输出或者再放入
else if(c=='+'||c=='-'){
if(isEmpty(head)) Push(head,c);
else{
do{
e=Pop(head);
if(e=='('){
Push(head,'(');
}
else cout<<" "<<e;
}while(e!='('&&!isEmpty(head));//关键!!
Push(head,c);
}
}
else if(c=='*'||c=='/'||c=='('){
Push(head,c);
}
else if(c=='#'){
break;
}
else{
cout<<"用户输入错误"<<endl;
return -1;
}
cin>>c;
}
while(!isEmpty(head)){
e=Pop(head);
cout<<" "<<e;
}
return 0;
}
2 判断的时候无结束符
//判断的时候无结束符
//就用string哈哈哈
#include<bits/stdc++.h>
#include<ctype.h>
using namespace std;
#define Maxsize 100
typedef struct Stack{
int data[Maxsize];//0~Maxsize-1
int top;
}Stack,*pStack;
pStack CreateStack(){
pStack head=new Stack();
head->top=-1;
return head;
}
bool isFull(pStack L){
if(L->top ==Maxsize-1) return true;
return false;
}
bool isEmpty(pStack L){
if(L->top ==-1) return true;
return false;
}
bool Push(pStack L,char e){
if(isFull(L)) return false;
L->data [++(L->top)]=e;
return true;
}
char Pop(pStack L){
if(isEmpty(L)) return false;
return L->data [(L->top )--];
}
int main(){
pStack head;
head=CreateStack();
string ss;char e;cin>>ss;
bool ismatch=true;
for(int i=0;ss[i];i++){
while(isdigit(ss[i])||ss[i]=='.'){
//是第一次
if(i==0){
cout<<ss[i];
i++;
}
//不连着 不是第一次
else if(!ismatch&&(i!=0)){
cout<<" "<<ss[i];
i++;
}
//连着的时候
else if(ismatch){
cout<<ss[i];
i++;
}
if(!isdigit(ss[i])&&ss[i]!='.'){
ismatch=false;
break;
}
else{
ismatch=true;
}
}
if(ss[i]==')'){
e=Pop(head);
while(e!='('){
cout<<" "<<e;
e=Pop(head);
}
}
//如果是+-的话,就把栈顶元素 1弹出判断优先级 2输出或者再放入
else if(ss[i]=='+'||ss[i]=='-'){
if(isEmpty(head)) Push(head,ss[i]);
else{
do{
e=Pop(head);
if(e=='('){
Push(head,'(');
}
else cout<<" "<<e;
}while(e!='('&&!isEmpty(head));//关键!!
Push(head,ss[i]);
}
}
else if(ss[i]=='*'||ss[i]=='/'||ss[i]=='('){
Push(head,ss[i]);
}
}
while(!isEmpty(head)){
e=Pop(head);
cout<<" "<<e;
}
return 0;
}
PTA上面需要考虑前缀符号的问题,那道题单独记录一下