Skip to content
This repository was archived by the owner on May 22, 2026. It is now read-only.

Commit ee24ffc

Browse files
feat: stack
1 parent 0a8a0d8 commit ee24ffc

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

data_structure/README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,13 @@
33
## スタック(Stack)
44

55
- Last In First Out でデータを取り出す構造
6-
- データが入るリストとスタックポインタとなる変数を用意してデータを入れた時にスタックポインタを増やして,データを取り出した時にスタックポインタを減らす。
6+
- 逆ポーランド記法(Reverse Polish Notation)の計算に利用される。
7+
8+
### 実装例
9+
10+
- [x] Python
11+
- [x] C
12+
- [x] Haskell: これだけ逆ポーランド記法の例。(Haskellのリストは単方向連結リストとして実装されているためスタックといって差し支えないため、応用例を変わりに実装)
713

814
---
915

data_structure/stack_/rpn.hs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
rpn :: [String] -> [Int]
2+
rpn input = foldl step [] input
3+
where
4+
step :: [Int] -> String -> [Int]
5+
step stack operand =
6+
case operand of
7+
"+" -> let (a : b : rest) = stack in (b + a) : rest
8+
"-" -> let (a : b : rest) = stack in (b - a) : rest
9+
"*" -> let (a : b : rest) = stack in (b * a) : rest
10+
n -> (read :: String -> Int) n : stack
11+
12+
main :: IO ()
13+
main = do
14+
print $ rpn $ words "4 8 + 1 3 + *" -- (4 + 8) * (1 + 3)

0 commit comments

Comments
 (0)