Skip to content

Instantly share code, notes, and snippets.

@radityopw
Created September 5, 2010 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save radityopw/566040 to your computer and use it in GitHub Desktop.
Save radityopw/566040 to your computer and use it in GitHub Desktop.
class Node
attr_writer :data, :index, :next, :prev
attr_reader :data, :index, :next, :prev
end
class My_list
attr_reader :node,:total
def add(data)
if @total == nil
@total = 1
else
@total = @total + 1
end
if @node == nil
@parent = Node.new
@node = Node.new
@node.data=data
@node.index = @total-1
@parent.next = @node
else
node = Node.new
node.data=data
node.index = @total-1
if @node.next == nil
node.prev = @node
@node.next=node
else
last_node = @node
while last_node.next != nil do
last_node = last_node.next
end
last_node.next = node
node.prev = last_node
end
end
end
def each
node = @parent
while node.next != nil do
node = node.next
yield(node.data)
end
end
def find_first
node = @node
for i in 0 ... @total do
value = node.data
return value if yield(value)
node = node.next
end
return nil
end
def find
node = @node
list = nil
for i in 0 ... @total do
value = node.data
if yield(value)
list = My_list.new unless list
list.add(node.data)
end
node = node.next
end
return list
end
def inject(n)
each do |value|
n = yield(n,value)
end
return n
end
def sum
inject(0) do |n,value|
n+value
end
end
def product
inject(1) do |n,value|
n * value
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment