C#用栈来输出后缀表达式

来源:互联网 发布:淘宝提高动态评分 编辑:程序博客网 时间:2024/05/16 06:36

后缀表达式如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;
     }
    }
   }
  } 

原创粉丝点击