【发布时间】:2014-05-22 22:07:58
【问题描述】:
我需要编写程序,但我无法完成它并弄乱了方法。 目的是找到所有正元素的总和并将其添加到最后。我刚刚开始教授课程和方法。
如何计算最终数组中所有正元素的总和?
这是我的代码:
class Node
attr_accessor :value, :next_node
def initialize val,next_in_line
@value = val
@next_nodex = next_in_line
puts "Initialized a Node with value: " + value.to_s
end
end
class LinkedList
def initialize val
@head = Node.new(val,nil)
end
def add(value)
current = @head
while current.next_node != nil
current = current.next_node
end
current.next_node = Node.new(value,nil)
self
end
def delete(val)
current = @head
if current.value == val
@head = @head.next_node
else
current = @head
while (current != nil) && (current.next_node != nil) && ((current.next_node).value != val)
current = current.next_node
end
if (current != nil) && (current.next_node != nil)
current.next_node = (current.next_node).next_node
end
end
end
def display
current = @head
full_list = []
while current.next_node != nil
full_list += [current.value.to_s]
current = current.next_node
end
full_list += [current.value.to_s]
puts full_list.join(" ")
end
def sum
end
end
puts "\n"
list = [*-99..99].shuffle
ll = LinkedList.new(list[0])
(1..9).each do |i|
ll.add(list[i])
end
puts "\nDo you want item to add? '1' - yes '0' - no"
adding = gets.to_i
puts "\n"
if adding == 1
ll.add(list[10])
end
puts "\nDisplaying Linked List:"
ll.display
puts "\nDo you want to delete item? '1' - yes '0' - no"
deleting = gets.to_i
if deleting == 1
puts "Type in and delete item and then display the linked list:"
deleteInt = gets.to_i
ll.delete(deleteInt)
end
puts ll.display
puts "\nThe sum of all positive elements"
ll.sum
【问题讨论】:
-
您需要提供一个问题。
-
您创建了一个数组调用
list,其中包含 -99 到 99 之间的 199 个整数(已洗牌)。然后创建LinkedList的实例ll,传递list的第一个元素。这不会让ll访问list,只能访问第一个元素,它是一个整数。 -
@CarySwoveland 我没有正确理解......我创建了包含 10 个初始元素的列表。但是如何将所有这些ll和list连接起来,以防收到list数组的所有正整数之和?
标签: ruby arrays linked-list sum