Home > Back-end >  The first algorithm C language
The first algorithm C language

Time:11-18

Want to ask why bosses into stack failed, please bosses and see children QWQ



#include
#include
#include
Typedef struct {
Char base [20].
Char top;
} charstack;

Typedef struct {
Int base [20];
int top;
} numstack;

Void Pushchar charstack * s, char (x)//insert character x
{
S - & gt; The base/s - & gt; top=x;
S - & gt; Top + +;
}

Void Pushnum (numstack * s, int x)//insert number x
{
S - & gt; The base/s - & gt; top=x;
S - & gt; Top + +;
}

Void Popnum (numstack * s, int * x)//pop up digital x
{
X=& amp; S - & gt; The base [s - & gt; top];
S - & gt; Top -;
}

Void Popchar (charstack * s, char * x)//pop-up character x
{
X=& amp; S - & gt; The base [s - & gt; top];
S - & gt; Top -;
}

Int getIndex (char theta)//get theta corresponding index
{
Int index=0;
The switch (theta)
{
Case: '+'
index=0;
break;
In case the '-' :
The index=1;
break;
Case: '*'
The index=2;
break;
Case '/' :
The index=3;
break;
Case '('
The index=4;
break;
Case ') :
The index=5;
break;
Case '#' :
The index=6;
Default: break;
}
return index;
}


Int Operate (int, char op, int b)//operation
{
The switch (op)
{
A case of '+' : the return of a + b; break;
Case '-' : return a - b; break;
Case '*' : return a * b; break;
Case '/' : the return of a/b; break;
Default: return 0; break;
}
}

Int the find (int a, int b)//construct priority relational table
{
Int table [7] [7]={
1, 1, 1, 1, 1,1,1,
1, 1, 1, 1, 1,1,1,
,1,1,1,1,1, 1-1,
,1,1,1,1,1, 1-1,
1, 1, 1, 1, 1,0,2,
1,1,1,1,2,1,1,
1, 1, 1, 1, 1 0
};
Return the table [a] [b];
}

Int main ()//operator priority algorithm
{
Charstack OPTR;
Numstack OPND;
OPTR. Top=0;
OPND. Top=0;
Char c, q;
Char x, y;
Int a=0, b=0, t=0, f=0;
Pushchar (& amp; OPTR, '#');
Popchar (& amp; OPTR, & amp; Y);
Printf (" % c ", y);
C=getchar ();
Q='#';
While (c!='#' | | q!='#')
{

If (c>='0' & amp; & C<='9')
{
T=c - '0';
Pushnum (& amp; OPND, t);
C=getchar ();
}
Else if (c=='+' | | c=='-' | | c=='*' | | c=='/' | | c=='(' | | c==') '| | c==' # ')
{
F=find (getIndex (q), getIndex (c));
If (f==1)
{
Pushchar (& amp; OPTR, c);
C=getchar ();
}
Else if (f==0)
{
Popchar (& amp; OPTR, & amp; X);
C=getchar ();
}
Else if (f==1)
{
Popnum (& amp; OPND, & amp; A);
Popnum (& amp; OPND, & amp; B);
Popchar (& amp; OPTR, & amp; Y);
Pushnum (& amp; OPND to Operate (a, y, b));
C=getchar ();
}

Popchar (& amp; OPTR, & amp; Y);
Q=y;
Pushchar (& amp; OPTR, y);
}

}
Popnum (& amp; OPND, & amp; T);
Printf (" % d \ n ", t);
return t;
}

CodePudding user response:

Note after each input '\ n' residual in the input buffer, the next getchar () will receive the '\ n'
  • Related