在 Ruby 中添加节点时出现 NoMethodError

NoMethodError while adding node in Ruby

我正在尝试在 ruby 中打印链表,但出现错误 add': undefined method `next=' for # (NoMethodError ) 知道我应该做什么吗?

class Node
    def initialize data
        @data = data
        @next = nil
    end
end

class LinkedList
    def initialize
        @head = nil
    end
    def add data
        temp = @head
        @head = Node.new(data)
        @head.next = temp
    end
    def printList
        temp = @head
        while temp
            puts temp.data
            temp = temp.next
        end
    end
end

list = LinkedList.new
list.add(1)
list.add(2)
list.add(3)

list.printList()

为了访问 next 属性的 setter,我建议将 attribute_accessor 添加到 Node

class Node
  attr_accessor :next

  def initialize(data)
    @data = data
  end
end

这将为您的 Node 实例中的下一个属性生成 settergetter

此外,我还会向 Node 添加一个 attr_reader,以便您可以从实例外部访问 data

class Node
  attr_accessor :next
  attr_reader :data

  def initialize(data)
    @data = data
  end
end