mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-24 23:50:45 +08:00
Migrate init_array, hash_map_operations, hash_map_traversal, queue_operations, deque_operations and insert_remove_node: zh and ru demo sources gain region markers and the snippets' comments, en, ja and ko are regenerated from reviewed translations, zh-hant via OpenCC. 70 blocks become region references; builtin_hash and five blocks without reviewed translations stay literal. The Java, Kotlin and Rust deque demos follow the book's order, and a few demo comments and typos are aligned with the snippets. Co-Authored-By: Claude Opus 5.5 <[email protected]>
59 lines
1.8 KiB
Ruby
59 lines
1.8 KiB
Ruby
=begin
|
|
File: deque.rb
|
|
Created Time: 2024-04-06
|
|
Author: Xuan Khoa Tu Nguyen ([email protected])
|
|
=end
|
|
|
|
### 実行用コード ###
|
|
if __FILE__ == $0
|
|
# [region]{init_deque}
|
|
# 両端キューを初期化する
|
|
# Ruby には組み込みの両端キューがないため、Array を両端キューとして使うしかない
|
|
deque = []
|
|
# [endregion]{init_deque}
|
|
|
|
# [region]{push}
|
|
# 要素をエンキューする
|
|
deque << 2
|
|
deque << 5
|
|
deque << 4
|
|
# 配列なので Array#unshift メソッドの時間計算量は O(n) であることに注意
|
|
deque.unshift(3)
|
|
deque.unshift(1)
|
|
# [endregion]{push}
|
|
puts "両端キュー deque = #{deque}"
|
|
|
|
# [region]{peek_first}
|
|
# 要素にアクセスする
|
|
peek_first = deque.first
|
|
# [endregion]{peek_first}
|
|
puts "キューの先頭要素 peek_first = #{peek_first}"
|
|
# [region]{peek_last}
|
|
peek_last = deque.last
|
|
# [endregion]{peek_last}
|
|
puts "キューの末尾要素 peek_last = #{peek_last}"
|
|
|
|
# [region]{pop_first}
|
|
# 要素をデキューする
|
|
# 配列なので Array#shift メソッドの時間計算量は O(n) であることに注意
|
|
pop_front = deque.shift
|
|
# [endregion]{pop_first}
|
|
puts "先頭からデキューした要素 pop_front = #{pop_front}、先頭からデキューした後 deque = #{deque}"
|
|
# [region]{pop_last}
|
|
pop_back = deque.pop
|
|
# [endregion]{pop_last}
|
|
puts "末尾からデキューした要素 pop_back = #{pop_back}, 末尾からデキューした後 deque = #{deque}"
|
|
|
|
# [region]{size}
|
|
# 両端キューの長さを取得する
|
|
size = deque.length
|
|
# [endregion]{size}
|
|
puts "両端キューの長さ size = #{size}"
|
|
|
|
# [region]{is_empty}
|
|
# 両端キューが空かどうかを判定する
|
|
is_empty = size.zero?
|
|
# [endregion]{is_empty}
|
|
puts "両端キューは空か = #{is_empty}"
|
|
end
|