Ruby链表、append和prepend方法
我在学习如何指向新值以及添加新值时指针如何变化方面遇到了困难。使用prepend@head时等于新节点指针。当您使用prepend添加第二个值时,@head现在等于该节点指针。这是怎么回事?第一个节点指针如何变为零Ruby链表、append和prepend方法,ruby,linked-list,Ruby,Linked List,我在学习如何指向新值以及添加新值时指针如何变化方面遇到了困难。使用prepend@head时等于新节点指针。当您使用prepend添加第二个值时,@head现在等于该节点指针。这是怎么回事?第一个节点指针如何变为零 class Node attr_accessor :data, :next def initialize(data) @data = data end end class LinkedList attr_accessor :head def ini
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)
我的append方法将创建一个新节点,但当我第二次尝试使用append时,它只会覆盖第一次。我不明白它是如何在prepend中每次添加一个新节点的,但在append中,每次调用它时它都会覆盖第一个节点
def prepend(data)
current = Node.new(data)
current.next = @head
@head = current
end
假设
@head
是链表中的第一个元素。问题是,@head
不足以追加节点,因为前置
的逻辑应该是:“last
元素链接到前置节点,前置节点成为新的last
元素”
这就是为什么LinkedList
的逻辑转换为:
def append(data)
@head = Node.new(data)
end
由于空列表已初始化,@tail
和@head
需要分配给第一个附加/前置节点每个
方法仅用于方便打印结果:
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
请注意,
append
和prepend
方法基本相同,可以通过使用Ruby
块删除重复的代码来重构。请修复代码的缩进。主要是,您不想缩进类LinkedList
。我认为您不是在更新上一个节点的下一个节点,您将在其中追加新节点。“我不明白”是一个语句,而不是一个问题。你的问题是什么?卡里,下课后的东西不是应该用两个空格缩进吗?
test = LinkedList.new
test.prepend(5)
test.prepend(2)
test.prepend(9)
test.append(111)
test.append(222)
test.each { |node| puts node.data }