Skip to content

Instantly share code, notes, and snippets.

@neoeno
Last active November 6, 2024 23:09
Show Gist options
  • Save neoeno/a0adbbcbe8e40d35d5c77e2a983903de to your computer and use it in GitHub Desktop.
Save neoeno/a0adbbcbe8e40d35d5c77e2a983903de to your computer and use it in GitHub Desktop.
Linked List Challenge
class LinkedList
attr_reader :head
attr_accessor :tail
def self.from_ruby_list(list)
return nil if list.empty?
new(list[0], self.from_ruby_list(list[1..]))
end
def initialize(head, tail = nil)
validate_tail!(tail)
@head = head
@tail = tail
end
def inspect
"{#{head} -> #{tail.inspect}}"
end
private
def validate_tail!(tail)
return if tail.is_a? LinkedList
return if tail.nil?
fail "Tail must be a LinkedList or nil, given #{tail.class}."
end
end
# Want more info on linked lists?
# Try here: https://www.rubyguides.com/2017/08/ruby-linked-list/
puts "== Trying out some features =="
list = LinkedList.new('a', LinkedList.new('b', nil))
p list
# {a -> {b -> nil}}
p list.head
# => "a"
p list.tail
# => {b -> nil}
p list.tail.head
# => "b"
p list.tail.tail
# => nil
puts
puts "== Changing the tail =="
list.tail = LinkedList.new('bat', LinkedList.new('rat', nil))
p list
# => {a -> {bat -> {rat -> nil}}}
puts
puts "== Trying a longer one =="
puts LinkedList.from_ruby_list([1, 2, 3, 4, 5]).inspect
# => {1 -> {2 -> {3 -> {4 -> {5 -> nil}}}}}
def reverse(list, new_tail = nil)
# The challenge is to reverse the given `list` without initialising any
# new LinkedLists or amending the LinkedList class. Note that you _can_
# change the tail for each item.
end
puts
puts "== Reversing! =="
puts reverse(LinkedList.from_ruby_list([1, 2, 3, 4, 5])).inspect
# => {5 -> {4 -> {3 -> {2 -> {1 -> nil}}}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment