Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program RPN;
- uses Contnrs;
- var
- s: String; //Input string
- stack: TStack; //Working RPN stack
- a, b, r: LongInt; //Two operands and result
- pa, pb, pr: ^LongInt;
- op: Char;
- buf: String; //Holds a single operand or operator
- i, l, head, tail: Integer; // Input string parser pointers
- begin
- ReadLn(s);
- s := s + ' ';
- i := 0; //infinite loop detection
- (* New(pa);
- New(pb);
- New(pr); *)
- a:=-1; pa := @a;
- b:=-1; pb := @b;
- r:=-1; pr := @r;
- stack := TStack.Create;
- repeat
- head := 1;
- tail := Pos(' ', s);
- buf := Copy(s, head, tail-head);
- op := buf[1];
- case op of // Pascal case does not fall through!
- '+':
- begin
- pa := stack.Pop; a:=pa^;
- pb := stack.Pop; b:=pb^;
- r := a + b;
- stack.Push(pr);
- end;
- '-':
- begin
- pa := stack.Pop; a:=pa^;
- pb := stack.Pop; b:=pb^;
- r := a - b;
- stack.Push(pr);
- end;
- '*':
- begin
- pa := stack.Pop; a:=pa^;
- pb := stack.Pop; b:=pb^;
- r := a * b;
- stack.Push(pr);
- end;
- '0'..'9':
- begin
- Val(buf,r); pr:=@r;
- stack.Push(pr);
- end;
- end; //case
- // WriteLn(buf); //debug
- Delete(s, head, tail-head+1); // delete the space as well
- Inc(i); //infinite loop detection
- l := Length(s);
- until (l=0) or (i>32768);
- // WriteLn(s); // is empty
- pr := stack.Pop;
- WriteLn(pr^);
- (*Dispose(pa);
- Dispose(pb);
- Dispose(pr);*)
- stack.Destroy;
- // ReadLn;
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement