0

再帰を使用してプレフィックス式を解析するコードを探しています。主にC++ですが、他の言語でも使用できます。翻訳します。ありがとう。

4

1 に答える 1

1

自分で行うのは非常に簡単です (必要なのは、演算子のスタック (および場合によってはその最初の用語) だけです)。

しかし、本当に多くの作業をしたくない場合は、次のリンクを参照してください。

プレフィックス表記文字列から int への変換

再帰を使用する必要がある場合は、基本的に関数内のローカル変数をスタック内の個々の要素として使用します。

例えば。疑似 C++ コードは次のとおりです。

int naughtyglobalendindex = 0;
int parse(string str) {

  if (/* str starts off with an integer */) return the integer;

  char operator;
  operator = ?? // you will need to get the first op here. Maybe sscanf(str,"%c",&operator) or similar

  // get first argument
  int first = parse(/* str with 1st operator removed */);
  // get 2nd integer argument
  int second = parse(/* str - get substring from naughtyglobalendindex to end*/)

  // return first operator second <- this is pseudocode
  // in effect you want a switch clause
  switch (operator) {
    case '+': return first + second;
    case '-': return first - second; // and so on
  }
}

疑似コードを実際の C++ に変換し、必要に応じてグローバルnaughtyglobalendindex変数を修正できます。

于 2012-08-19T00:01:49.903 に答える