Files
hello-algo/en/codes/ruby/utils/list_node.rb
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

39 lines
708 B
Ruby

=begin
File: list_node.rb
Created Time: 2024-03-18
Author: Xuan Khoa Tu Nguyen (ngxktuzkai2000@gmail.com)
=end
### Linked list node class ###
class ListNode
attr_accessor :val # Node value
attr_accessor :next # Reference to the next node
def initialize(val=0, next_node=nil)
@val = val
@next = next_node
end
end
### Deserialize a list into a linked list ###
def arr_to_linked_list(arr)
head = current = ListNode.new(arr[0])
for i in 1...arr.length
current.next = ListNode.new(arr[i])
current = current.next
end
head
end
### Serialize a linked list into a list ###
def linked_list_to_arr(head)
arr = []
while head
arr << head.val
head = head.next
end
end