【发布时间】:2012-05-05 16:27:59
【问题描述】:
我用 ruby 创建了一个单独的 LinkedList 类。 一切都很顺利,直到尝试反转链表。
这种方法并没有反向链表,但是当我添加 @head.next = 无 在 reverse 方法中 left_tmp = @head 之后,它就可以正常工作了。
当我添加它时,我无法弄清楚为什么它会起作用,有人解释一下吗?
顺便说一句,我对 ruby 还很陌生,所以请不要犹豫,告诉我是否还有一些不是“Ruby 中的良好实践”的东西。
这里是类和相关方法:
class LlNode
attr_reader :data
attr_accessor :next
def initialize(val=nil)
@data = val
@next = nil
end
def to_s
"node_data=#{@data}"
end
end
class LinkedList
def initialize
@list = []
@head = LlNode.new
end
def insert(val)
n = LlNode.new val
# List is empty
if is_empty?
@head = n
else
n.next = @head
@head = n
end
self
end
def reverse
return if is_empty? or @head.next.nil?
curr = @head.next
right_tmp = curr.next
left_tmp = @head
while curr != nil
curr.next = left_tmp
left_tmp = curr
curr = right_tmp
right_tmp = right_tmp.next unless right_tmp.nil?
end
@head = left_tmp
end
end
【问题讨论】:
标签: ruby linked-list