Einzelnen Beitrag anzeigen

Benutzerbild von Luckie
Luckie

Registriert seit: 29. Mai 2002
37.621 Beiträge
 
Delphi 2006 Professional
 
#9

Re: Stack: Infix nach Postfix und push und pop

  Alt 14. Mär 2010, 10:53
Danke für eure Mühe, insbesondere himitsu. Allerdings gibt es da ein kleines Problem:
Delphi-Quellcode:
function Infix2Postfix(const S: String): String;
var
  i: Integer;
begin
  Result := '';
  init;
  for i := 1 to Length(S) do
    case S[i] of
      ')': Result := Result + chr(pop);
      '+': push(ord(S[i]));
      '*': push(ord(S[i]));
      '0'..'9': Result := Result + S[i];
    end;
end;

function CalcPostfix(const S: String): String;
var
  i, x: Integer;
begin
  Result := '';
  i := 1;
  while i <= Length(S) do begin
    x := 0;
    case S[i] of
      '*': x := pop * pop;
      '+': x := pop + pop;
      '0'..'9': begin
        x := ord(S[i]) - ord('0');
        while (i < Length(S)) and (S[i + 1] >= '0') and (S[i + 1] <= '9') do begin
          Inc(i);
          x := 10 * x + (ord(S[i]) - ord('0'));
        end;
      end;
    end;
    push(x);
    Inc(i);
  end;
  Result := Result + IntToStr(pop);
end;
Bei der Umwandlung von Infix nach Postfix geht das Rechenzeichen verloren. aus 5 + 6 wird nur 56. das hat natürlich zur Folge das CalcPostfix nix macht.

Aufruf:
Delphi-Quellcode:
  Init;
  Readln(s);
  s := Infix2Postfix(s);
  Writeln(s);
  Init;
  s := CalcPostfix(s);
  Writeln(s);
  Readln;
Eingabe:
Code:
5 + 6
Aber auch wenn ich CalcPostFix
Code:
5 6 +
übergebe, bekomme ich als Ausgabe nur 6.

Da ist also noch irgendwo der Wurm drin. Kann natürlich auch an meinem Stack liegen, dass der fehlerhaft ist, siehe oben.
Michael
Ein Teil meines Codes würde euch verunsichern.
  Mit Zitat antworten Zitat