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
- op: Char;
- buf: String; //Holds a single operand or operator
- l, head, tail: Integer; // Input string parser pointers
- procedure my_Push(var stack: TStack; r: LongInt);
- var pr: ^LongInt;
- begin
- New(pr);
- pr^ := r;
- stack.Push(pr);
- end;
- function my_Pop(var stack: TStack) : LongInt;
- var pv: ^LongInt;
- begin
- pv := stack.Pop();
- if pv = nil
- then WriteLn('Stack is already empty!');
- my_Pop := pv^;
- Dispose(pv);
- end;
- begin
- // WriteLn('Enter an expression in RPN notation: ');
- ReadLn(s);
- s := s + ' ';
- stack := TStack.Create;
- repeat
- head := 1;
- tail := Pos(' ', s);
- if tail = head then begin
- Delete(s, head, tail-head+1);
- l := Length(s);
- continue; // skip leading spaces
- end;
- buf := Copy(s, head, tail-head);
- op := buf[1];
- case op of // Pascal case does not fall through!
- '+':
- begin
- b := my_Pop(stack);
- a := my_Pop(stack);
- r := a + b;
- my_Push(stack, r);
- end;
- '-':
- begin
- b := my_Pop(stack);
- a := my_Pop(stack);
- r := a - b;
- my_Push(stack, r);
- end;
- '*':
- begin
- b := my_Pop(stack);
- a := my_Pop(stack);
- r := a * b;
- my_Push(stack, r);
- end;
- '/':
- begin
- b := my_Pop(stack);
- if b = 0
- then WriteLn('Attempting division by zero!');
- a := my_Pop(stack);
- r := a div b;
- my_Push(stack, r);
- end;
- '0'..'9':
- begin
- Val(buf,r);
- my_Push(stack, r);
- end;
- end; //case
- Delete(s, head, tail-head+1); // delete the space as well
- l := Length(s);
- until (l=0);
- r := my_Pop(stack);
- WriteLn(r);
- stack.Destroy;
- // ReadLn;
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement