您好我试图在ruby的链接列表中的特定索引处插入一个值。
到目前为止,这是我的代码:
class Node
attr_accessor :data, :pointer, :next
def initialize(data, pointer = nil)
@data = data
@pointer = pointer
end
def next
@data = @pointer
end
end
class LinkedList
attr_accessor :head, :data, :pointer
def initialize(data)
@head = Node.new(data, pointer)
end
def index_at(value_of_index)
current = head
value_of_index.times do
if current.pointer == nil
current = Node.new(nil, nil)
return current = current.data
else
current = current.next
end
end
current.data
end
def insert_at_index(index, value)
current = head
index.times do
current.next
end
current = Node.new(value)
end
end
我遇到的问题是使用def insert_at_index方法......我似乎无法弄清楚如何将新节点放在索引和值上。您将给予我的任何帮助将不胜感激。
答案 0 :(得分:1)
假设您的链接列表如下所示:
a -> b -> d -> e
要将c
插入第3个索引,您将移至第二个索引以获取b
,创建新节点,在新节点{{旁边设置b
1}},并在旧的第三个索引项c
旁边设置c
。
这会给你:
d
那就是说,代码应该是这样的:
a -> b -> c -> d -> e
从它的外观来看,你的代码似乎还有其他问题。你在下一个函数中覆盖了def insert_at_index(index, value)
current = head
# make current b. You may want to put this in a function node_at_index
(index - 1).times do
raise "List not long enough" if current.nil?
current = current.next
end
new_node = Node.new(value) # new node c
new_node.next = current.next # c's next is b's next, d
current.next = new_node # b's next is c
end
(你可能只是@data
},return @pointer
没有定义LinkedList#initialize
等等
您可以将Node简化为:
pointer
哪个应该适合你。
答案 1 :(得分:0)
这是一个对我有用的解决方案:
class Node
attr_accessor :data, :pointer
alias_method :next, :pointer
def initialize(data, pointer = nil)
@data = data
@pointer = pointer
end
def next
@pointer
end
end
class LinkedList
attr_accessor :head, :data, :pointer
def initialize(data)
@head = Node.new(data, pointer)
end
def index_at(value_of_index)
current = head
value_of_index.times do
if current.pointer == nil
current = Node.new(nil, nil)
return current = current.data
else
current = current.next
end
end
current.data
end
def insert_at_index(index, value)
current = head
(index - 1).times do
if current.pointer != nil
current = current.next
end
end
new_node = Node.new(value)
if current.pointer != nil
new_node.pointer = current.pointer
end
current.pointer = new_node
end
end