spondon.majumdar1
BAN USERRuby implementation should be like this
class Node
attr_accessor :value, :next_node
def initialize(value,next_node)
@value = value
@next_node = next_node
end
end
class LinkList
def initialize(value)
@head = Node.new(value,nil)
end
def add_to_linklist(value)
puts "Inserting value #{value.to_s}"
current = @head
while current.next_node != nil
current = current.next_node
end
current.next_node = Node.new(value,nil)
self
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 print_the_second_last_node
list = []
second_last_node = nil
current = @head
puts "you have only one element in link list" if current.next_node == nil
while current.next_node != nil
list.push(current.value.to_s)
current = current.next_node
end
index= list.size - 1
puts "second last node is #{list[index]}"
end
end
obj = LinkList.new(10)
obj.add_to_linklist(6)
obj.add_to_linklist(15)
obj.add_to_linklist(20)
obj.print_the_second_last_node
obj.display
Rough solution, yes we can do some more optimization but I believe code readability is great
- spondon.majumdar1 August 18, 2015