Skip to content

Instantly share code, notes, and snippets.

@tomcha
Created December 31, 2015 08:12
Show Gist options
  • Select an option

  • Save tomcha/b6a619ab5bdf5ef10234 to your computer and use it in GitHub Desktop.

Select an option

Save tomcha/b6a619ab5bdf5ef10234 to your computer and use it in GitHub Desktop.
逆ポーランド記法
#!/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