hello-algo/zh-hant/codes/ruby/utils/print_util.rb
Yudong Jin f616dac7da
Bug fixes and improvements (#1298)
* Fix is_empty() implementation in the stack and queue chapter

* Update en/CONTRIBUTING.md

* Remove "剩余" from the state definition of knapsack problem

* Sync zh and zh-hant versions

* Update the stylesheets of code tabs

* Fix quick_sort.rb

* Fix TS code

* Update chapter_paperbook

* Upload the manuscript of 0.1 section

* Fix binary_tree_dfs.rb

* Bug fixes

* Update README

* Update README

* Update README

* Update README.md

* Update README

* Sync zh and zh-hant versions

* Bug fixes
2024-04-22 02:26:32 +08:00

63 lines
1.2 KiB
Ruby

=begin
File: print_util.rb
Created Time: 2024-03-18
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### 列印鏈結串列 ###
def print_linked_list(head)
list = []
while head
list << head.val
head = head.next
end
puts "#{list.join(" -> ")}"
end
class Trunk
attr_accessor :prev, :str
def initialize(prev, str)
@prev = prev
@str = str
end
end
def show_trunk(p)
return if p.nil?
show_trunk(p.prev)
print p.str
end
### 列印二元樹 ###
# This tree printer is borrowed from TECHIE DELIGHT
# https://www.techiedelight.com/c-program-print-binary-tree/
def print_tree(root, prev=nil, is_right=false)
return if root.nil?
prev_str = " "
trunk = Trunk.new(prev, prev_str)
print_tree(root.right, trunk, true)
if prev.nil?
trunk.str = "———"
elsif is_right
trunk.str = "/———"
prev_str = " |"
else
trunk.str = "\\———"
prev.str = prev_str
end
show_trunk(trunk)
puts " #{root.val}"
prev.str = prev_str if prev
trunk.str = " |"
print_tree(root.left, trunk, false)
end
### 列印雜湊表 ###
def print_hash_map(hmap)
hmap.entries.each { |key, value| puts "#{key} -> #{value}" }
end