!****************************************************! Stack モジュール!! date name version! 2018.08.21 mk-mode.com 1.00 新規作成!! Copyright(C) 2018 mk-mode.com All Rights Reserved.!****************************************************!module stackimplicit none private! デフォルトを private に設定public::pop,push! pop, push のみ public とする! 以下の変数は private となる。integer,parameter::pmax=256! スタックの最大長integer,save::buf(1:pmax)! スタック配列integer,save::p=0! 最後(トップ)の要素の位置contains! Pop from a stack! : スタックからトップノードを取り出すinteger function pop()implicit none if(p>0)thenpop=buf(p)! 最後の要素を取り出すp=p-1! 最後の要素の位置を左に 1 つずらすelse print*,"Stack underflow!"pop=-huge(p)end if end function pop! Push into a stack! : スタックに n をトップノードとして付け加える!! :param integer nsubroutine push(n)implicit noneinteger,intent(IN)::nif(p<pmax)thenp=p+1! 最後の要素の位置を右に 1 つずらすbuf(p)=n! 要素を付け加えるelse print*"Stack overflow!"end if end subroutine pushend module stack
そして、実行部分。
test_stack.f95
1234567891011121314151617181920212223242526
!****************************************************! テスト (Stack モジュール)!! date name version! 2018.08.21 mk-mode.com 1.00 新規作成!! Copyright(C) 2018 mk-mode.com All Rights Reserved.!****************************************************!program mainuse stackimplicit noneinteger::i! 1, 2, 3 を pushdo i=1,3call push(i)enddo! 3 回 popdo i=1,3print*,pop()enddostopend program main
!****************************************************! 逆ポーランド記法 (Stack モジュール使用)!! date name version! 2018.08.21 mk-mode.com 1.00 新規作成!! Copyright(C) 2018 mk-mode.com All Rights Reserved.!****************************************************!program mainuse stackimplicit nonecharacter(len=80)::bufinteger::iprint'(A)',"Calculator by Reverse Polish Notation."do read(*,'(A80)')bufif(len(trim(buf))==0)exit do i=1,len(trim(buf))select case(buf(i:i))case(" ")cycle case("0":"9")call push(ichar(buf(i:i))-ichar('0'))case("+")call push(pop()+pop())case("-")call push(-pop()+pop())case("*")call push(pop()*pop())case("=")exit case defaultprint*,"Unknown operator."exit end selectenddoprint'(A,I15)',"Ans: ",pop()enddostopend program main