Skip to content

Instantly share code, notes, and snippets.

@wmantly
Created August 18, 2018 22:39
Show Gist options
  • Save wmantly/df7103ed876eb9ac115d88ccd0d05255 to your computer and use it in GitHub Desktop.
Save wmantly/df7103ed876eb9ac115d88ccd0d05255 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
class Node
attr_accessor :data, :next_node
def initialize(data, next_node=nil)
@data = data
@next = next_node
end
end
class LinkedList
def initialize(*items)
@head = nil
if items
self.prepend(*items)
end
end
def prepend(*items)
items.reverse.each do |item|
old_head = @head
@head = Node.new(item)
@head.next_node = old_head
end
end
def append(*items)
last = @head
while last.next_node
last = last.next_node
end
items.each do |item|
new_node = Node.new(item)
last.next_node = new_node
last = new_node
end
end
def delete(target)
current = @head
last = @head
while current && current.data != target
last = current
current = current.next_node
end
if current
last.next_node = current.next_node
end
end
def length
count = 0
current = @head
while current
count += 1
current = current.next_node
end
return count
end
def show
current = @head
while current
puts current.data
current = current.next_node
end
end
def show_reverse
def rec(current)
if current
return "#{rec(current.next_node)} <- |#{current.data}|"
else
return 'Tail'
end
end
puts "#{rec(@head)} <- Head"
end
end
list = LinkedList.new('a','b','c')
list.append('d', 'f', 'g')
list.show()
puts list.length()
list.show_reverse()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment