Advertisement
ALTracer

RPN_52.pas

Dec 8th, 2020
945
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 1.54 KB | None | 0 0
  1. program RPN;
  2. uses Contnrs;
  3. var
  4.   s: String; //Input string
  5.   stack: TStack; //Working RPN stack
  6.   a, b, r: LongInt; //Two operands and result
  7.   pa, pb, pr: ^LongInt;
  8.   op: Char;
  9.   buf: String; //Holds a single operand or operator
  10.   i, l, head, tail: Integer; // Input string parser pointers
  11.  
  12. begin
  13.   ReadLn(s);
  14.   s := s + ' ';
  15.   i := 0; //infinite loop detection
  16. (*  New(pa);
  17.   New(pb);
  18.   New(pr); *)
  19.   a:=-1; pa := @a;
  20.   b:=-1; pb := @b;
  21.   r:=-1; pr := @r;
  22.   stack := TStack.Create;
  23.  
  24.   repeat
  25.     head := 1;
  26.     tail := Pos(' ', s);
  27.     buf := Copy(s, head, tail-head);
  28.  
  29.     op := buf[1];
  30.     case op of // Pascal case does not fall through!
  31.       '+':
  32.       begin
  33.         pa := stack.Pop; a:=pa^;
  34.         pb := stack.Pop; b:=pb^;
  35.         r := a + b;
  36.         stack.Push(pr);
  37.       end;
  38.       '-':
  39.       begin
  40.         pa := stack.Pop; a:=pa^;
  41.         pb := stack.Pop; b:=pb^;
  42.         r := a - b;
  43.         stack.Push(pr);
  44.       end;
  45.       '*':
  46.       begin
  47.         pa := stack.Pop; a:=pa^;
  48.         pb := stack.Pop; b:=pb^;
  49.         r := a * b;
  50.         stack.Push(pr);
  51.       end;
  52.       '0'..'9':
  53.       begin
  54.         Val(buf,r); pr:=@r;
  55.         stack.Push(pr);
  56.       end;
  57.     end; //case
  58. //    WriteLn(buf); //debug
  59.     Delete(s, head, tail-head+1); // delete the space as well
  60.  
  61.     Inc(i); //infinite loop detection
  62.     l := Length(s);
  63.   until (l=0) or (i>32768);
  64. //  WriteLn(s); // is empty
  65.  
  66.   pr := stack.Pop;
  67.   WriteLn(pr^);
  68.  
  69.   (*Dispose(pa);
  70.   Dispose(pb);
  71.   Dispose(pr);*)
  72.   stack.Destroy;
  73. //  ReadLn;
  74. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement