后缀表达式如a+b+c 后缀表达式为ab+c+,a+b*c为abc*+,a*(b+c)为abc+*
class StackX
{
private int maxsize;
private char[] stackarray;
private int top;
public StackX(int s)
{
maxsize=s;
stackarray=new char[maxsize];
top=-1;
}
public void push(char j)
{
stackarray[++top]=j;
}
public char pop()
{
return stackarray[top--];
}
public char peek()
{
return stackarray[top];
}
public bool isempty()
{
return (top==-1);
}
public int size()
{
return (top+1);
}
public char npeek(int n)
{
return stackarray[n];
}
public void display()
{
for(int i=0;i<size();i++)
{
Console.Write("{0},",npeek(i));
}
Console.WriteLine();
}
}
public class Stack
{
private StackX thestack;
private string input;
private string output="";
public Stack(string str)
{
input=str;
int len=input.Length;
thestack=new StackX(len);
}
public string dotrans()
{
for(int i=0;i<input.Length;i++)
{
char ch=(char)(input.ToCharArray(i,1).GetValue(0));
thestack.display();
switch(ch)
{
case '+':
case '-':
gotoper(ch,1);
break;
case '*':
case '/':
gotoper(ch,2);
break;
case '(':
thestack.push(ch);
break;
case ')':
gotparen(ch);
break;
default:
output+=ch;
break;
}
}
while(!thestack.isempty())
{
thestack.display();
output+=thestack.pop();
}
return output;
}
public void gotoper(char opthis,int prec1)
{
while(!thestack.isempty())
{
char optop=thestack.pop();
if(optop=='(')
{
thestack.push(optop);
break;
}
else
{
int prec2;
if(optop=='+' || optop=='-')
{
prec2=1;
}
else
{
prec2=2;
}
if(prec1>prec2)
{
thestack.push(optop);
break;
}
else
{
output+=optop;
}
}
}
thestack.push(opthis);
}
public void gotparen(char chr)
{
while(!thestack.isempty())
{
char ch=thestack.pop();
if(ch=='(')
{
break;
}
else
{
output+=ch;
}
}
}
}