class Node
attr_accessor :data, :next
def initialize(data)
@data = data
end
end
class LinkedList
attr_accessor :head
def initialize
@head = nil
end
def append(data)
@head = Node.new(data)
end
def prepend(data)
current = Node.new(data)
current.next = @head
@head = current
end
end
test = LinkedList.new
test.prepend(5)
test.prepend(2)
test.prepend(9)
test.append(111)
test.append(222)
我无法学习如何指向新值,以及添加新值时指针如何变化。使用前置@head等于新节点指针。当您使用prepend添加第二个值时,@ head现在等于该节点指针。这是如何运作的?第一个节点指针如何变为零?
def prepend(data)
current = Node.new(data)
current.next = @head
@head = current
end
我的append方法将创建一个新节点,但是当我尝试第二次使用append时它会覆盖第一个节点。我不明白它在前面是如何每次添加一个新节点,但是每次调用它时都会覆盖它。
def append(data)
@head = Node.new(data)
end
答案 0 :(得分:0)
提供@head
是链表中的第一个元素。问题是@head
不足以附加节点,因为prepend
的逻辑应该是:“last
元素链接到前置节点,前置节点成为新的{{ 1}}元素“。
这就是last
的逻辑变为:
LinkedList
由于初始化了空列表,因此需要将class LinkedList
attr_accessor :head, :tail
def initialize
@head = nil
@tail = nil
end
def append(data)
node = Node.new(data)
if empty?
@head = @tail = node
else
@tail.next = node
@tail = node
end
end
def prepend(data)
node = Node.new(data)
if empty?
@head = @tail = node
else
node.next = @head
@head = node
end
end
def empty?
@head.nil? && @tail.nil?
end
def each
node = @head
loop do
break unless node
yield node
node = node.next
end
end
end
和@tail
分配给第一个附加/前置节点。 @head
方法只是为了方便打印结果:
each
请注意,test = LinkedList.new
test.prepend(5)
test.prepend(2)
test.prepend(9)
test.append(111)
test.append(222)
test.each { |node| puts node.data }
和append
方法几乎相同,可以使用prepend
块删除重复的代码进行重构。