I am trying to print a linked list in ruby but getting the error add': undefined method `next=' for #<Node:0x000001c5c0738688 @data=1, @next=nil> (NoMethodError) any idea what i should do ?
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()
CodePudding user response:
In order to access the setter for the next
attribute I'd propose adding an attribute_accessor to Node
.
class Node
attr_accessor :next
def initialize(data)
@data = data
end
end
This will generate both a setter
and a getter
for the next attribute within your Node
instance.
Additionally I would also add an attr_reader
to Node
so that you can access data
from outside of the instance.
class Node
attr_accessor :next
attr_reader :data
def initialize(data)
@data = data
end
end