使用Ruby查找第n个节点值可以通过遍历链表来实现。以下是一个示例代码:
class Node
attr_accessor :value, :next
def initialize(value)
@value = value
@next = nil
end
end
class LinkedList
attr_accessor :head
def initialize
@head = nil
end
def add(value)
if @head.nil?
@head = Node.new(value)
else
current = @head
while current.next
current = current.next
end
current.next = Node.new(value)
end
end
def find_nth_node_value(n)
return nil if @head.nil?
current = @head
count = 1
while current && count < n
current = current.next
count += 1
end
current.nil? ? nil : current.value
end
end
# 创建链表并添加节点
linked_list = LinkedList.new
linked_list.add(1)
linked_list.add(2)
linked_list.add(3)
linked_list.add(4)
linked_list.add(5)
# 查找第n个节点的值
n = 3
value = linked_list.find_nth_node_value(n)
puts "第#{n}个节点的值为:#{value}"
这段代码创建了一个链表类(LinkedList)和节点类(Node)。链表类包含了添加节点的方法(add)和查找第n个节点值的方法(find_nth_node_value)。在示例中,我们创建了一个链表并添加了5个节点,然后查找第3个节点的值。
请注意,这只是一个简单的示例,实际应用中可能需要根据具体情况进行适当的修改和优化。
关于Ruby的更多信息和学习资源,你可以参考腾讯云的Ruby开发文档:Ruby开发指南。
领取专属 10元无门槛券
手把手带您无忧上云