Skip to content

Instantly share code, notes, and snippets.

@OfTheDelmer
Created December 2, 2013 20:07
Show Gist options
  • Save OfTheDelmer/7757528 to your computer and use it in GitHub Desktop.
Save OfTheDelmer/7757528 to your computer and use it in GitHub Desktop.
###
# Node List
###
class Node
attr_accessor :val, :next
def initialize(val, next_ref =nil)
@val=val
@next=next_ref
end
end
class List
attr_accessor :items
def initialize(*args)
# When it initializes its items are nil
@items = nil
make_list(args)
end
def insert_first(item)
# Set @items to a new Node with
# next = @items
# val = item to be added
@items = Node.new(item, @items)
end
def make_list(array)
# Terminal Condition
if array == []
return @items
else
insert_first(array.pop)
make_list(array)
end
end
# Just made these methods
def head
@items.val
end
def tail
@items.next
end
end
# let's write a function that will take an array
# and return a linked list
def make_list(array, my_list=List.new)
# Terminal Condition
if array == []
return my_list
else
my_list.insert_first(array.pop)
make_list(array,my_list)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment