我正在尝试构建一个程序,该程序将在Ruby中构建和操作双链表。
到目前为止,我已经能够满足告诉我我已经建立了列表的测试,但我正在努力让我的delete
方法正常工作。
现在我的 Rspec 测试一直告诉我:
Failure/Error: llist.delete(n3)
NameError:
undefined local variable or method `current' for #<LinkedList:0x007f85a49ae9b8>
Did you mean? current
即使我很确定我正在定义方法
这是我linkedlist.rb
文件
require_relative 'node'
class LinkedList
attr_accessor :head
attr_accessor :tail
bob = []
current = nil
# This method creates a new `Node` using `data`, and inserts it at the end of the list.
def add_to_tail(node)
if(@next)
@tail.next = node
else
@tail= node
end
end
# This method removes `node` from the list and must keep the rest of the list intact.
def delete(node)
current.next =@head
if current.node = node
@head =current.next
else
while (current.next != nil)&&(current.next.node != val)
current = current.next
end
unless current.next == nil
current.next =current.next.next
end
end
end
这是设置 Node
类的配套文件
class Node
attr_accessor :next
attr_accessor :data
def initialize(data)
@data = data
#@next = nil
end
end
这些是我试图通过的 Rspec 测试
include RSpec
require_relative 'node'
require_relative 'linked_list'
RSpec.describe LinkedList, type: Class do
let(:n1) { Node.new("Rob") }
let(:n2) { Node.new("Ben") }
let(:n3) { Node.new("Mike") }
let(:llist) { LinkedList.new }
describe "#add_to_tail" do
it "adds a Node to the tail" do
llist.add_to_tail(n1)
expect(llist.tail).to eq n1
llist.add_to_tail(n2)
expect(llist.tail).to eq n2
end
end
describe "#delete" do
before do
llist.add_to_tail(n1)
llist.add_to_tail(n2)
llist.add_to_tail(n3)
it "removes the correct node of a list properly" do
llist.delete(n1)
expect(llist.head).to eq n2
llist.delete(n3)
expect(llist.tail).to eq n2
end
您在类作用域中定义 current 和 Bob,但在 Ruby 类作用域中,变量使用双 @@ 设置。但是,在使用多个链表时,这会导致问题,因此在这种情况下您不希望使用类变量。因此,最好的方法是为 LinkedList 实例设置一个@current和@bob实例变量。我建议执行以下操作:
将电流和鲍勃更改为:
attr_accessor :current
attr_accessor :bob
attr_accessor
的作用是创建@current实例变量,并为您定义两个方法,一个 getter current
和一个 setter current=
。
将它们设置为 nil 和数组的下一步是使用 Initialize 方法,将其添加到您的 LinkedList
类中:
def initialize(*args)
@current = nil
@bob = []
end
虽然一旦创建了@current
实例,它就已经设置为 nil
,所以初始化中的第一行实际上是多余的,我只是为了显示目的而添加它,以便更容易看到正在发生的事情与你当前的代码相比。