Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby中实现LinkedList_Ruby_Linked List - Fatal编程技术网

在Ruby中实现LinkedList

在Ruby中实现LinkedList,ruby,linked-list,Ruby,Linked List,我试图在Ruby中实现一个单独链接的LinkedList,但我在试图弄清楚为什么一些节点正在消失时遇到了一些问题。以下是我目前掌握的情况: class Node attr_accessor :data, :next def initialize(data) @data = data end end class LinkedList attr_accessor :head def insert(data) node = Node.new(data)

我试图在Ruby中实现一个单独链接的LinkedList,但我在试图弄清楚为什么一些节点正在消失时遇到了一些问题。以下是我目前掌握的情况:

class Node
  attr_accessor :data, :next
  def initialize(data)
    @data = data
  end
end

class LinkedList
  attr_accessor :head

  def insert(data)
    node = Node.new(data)
    if @head.nil?
      @head = node
    else
      travel = @head
      unless travel.next.nil?
        travel = travel.next
      end
      travel.next = node
    end
    print @head
  end

  def to_string
    result = ""
    travel = @head
    unless travel.nil?
      result << "#{travel.data} => "
      travel = travel.next
    end
    result << "END"
    result
  end

end
在insert的末尾,我打印出
@head
,我可以看到所有三个节点都在列表中。但是,当我单独调用
to_string
时,
@head
只有第一个节点,但其他所有节点都没有了。有人能给我指出哪里出了问题吗


谢谢

关键字
有问题,除非
。在ruby中,它是一个条件语句,就像
if
一样。这不是一个循环。只需将它们替换为关键字
,直到

一般来说,链表的要点是在O(1)中插入,而在O(n)中插入(遍历列表并在末尾插入节点)。相反,您只需在开始处插入新节点即可

最后,ruby的约定是将to_string方法命名为to_s
,因此在打印列表时将调用它


此外,还可以将
节点
设置为
链接列表
的内部类。如果您想要实现其他基于节点的数据结构(deque、ring、tree等)

关键字
有问题,除非
。在ruby中,它是一个条件语句,就像
if
一样。这不是一个循环。只需将它们替换为关键字
,直到

一般来说,链表的要点是在O(1)中插入,而在O(n)中插入(遍历列表并在末尾插入节点)。相反,您只需在开始处插入新节点即可

最后,ruby的约定是将to_string方法命名为to_s
,因此在打印列表时将调用它


此外,还可以将
节点
设置为
链接列表
的内部类。如果您想要实现其他基于节点的数据结构(deque、ring、tree等),它将非常有用。

这可能会有所帮助吗?也许这能帮上忙?非常感谢。我会改变的,谢谢!我会做出改变的。
list = LinkedList.new
list.insert(5)
list.insert(6)
list.insert(7)