Last active
November 25, 2018 05:03
-
-
Save komasaru/6b8639f96bce5ad101ea2226f2c74e54 to your computer and use it in GitHub Desktop.
Fortran 95 source code to test stack implementation.
This file contains 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
!**************************************************** | |
! Stack モジュール | |
! | |
! date name version | |
! 2018.08.21 mk-mode.com 1.00 新規作成 | |
! | |
! Copyright(C) 2018 mk-mode.com All Rights Reserved. | |
!**************************************************** | |
! | |
module stack | |
implicit 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) then | |
pop = 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 n | |
subroutine push(n) | |
implicit none | |
integer, intent(IN) :: n | |
if (p < pmax) then | |
p = p + 1 ! 最後の要素の位置を右に 1 つずらす | |
buf(p) = n ! 要素を付け加える | |
else | |
print *, "Stack overflow!" | |
end if | |
end subroutine push | |
end module stack |
This file contains 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
!**************************************************** | |
! テスト (Stack モジュール) | |
! | |
! date name version | |
! 2018.08.21 mk-mode.com 1.00 新規作成 | |
! | |
! Copyright(C) 2018 mk-mode.com All Rights Reserved. | |
!**************************************************** | |
! | |
program main | |
use stack | |
implicit none | |
integer :: i | |
! 1, 2, 3 を push | |
do i = 1, 3 | |
call push(i) | |
enddo | |
! 3 回 pop | |
do i = 1, 3 | |
print *, pop() | |
enddo | |
stop | |
end program main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment