Created
December 31, 2015 08:12
-
-
Save tomcha/b6a619ab5bdf5ef10234 to your computer and use it in GitHub Desktop.
逆ポーランド記法
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env perl | |
| use strict; | |
| use warnings; | |
| use utf8; | |
| use open qw/:encoding(utf-8) :std/; | |
| use v5.12; | |
| use Data::Dumper; | |
| use DDP{deparse => 1}; | |
| my $str = '10 + 20 * 30 - 5 * 7'; | |
| my @arr = split(' ', $str); | |
| my @stack; | |
| my @rpn; | |
| for my $c (@arr){ | |
| if ($c eq '+' || $c eq '-'){ | |
| if(@stack > 0){ | |
| if ($stack[-1] eq '*' || $stack[-1] eq '/'){ | |
| while($stack[-1] eq '*' || $stack[-1] eq '/'){ | |
| push(@rpn, pop(@stack)); | |
| } | |
| } | |
| } | |
| push(@stack, $c); | |
| }elsif($c eq '*' || $c eq '/'){ | |
| push(@stack, $c); | |
| }else{ | |
| push(@rpn, $c); | |
| } | |
| } | |
| while (@stack > 0){ | |
| push(@rpn, pop(@stack)); | |
| } | |
| p @rpn; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment