Last active
December 22, 2015 16:19
-
-
Save vigram/6498628 to your computer and use it in GitHub Desktop.
Linear Linked List Implementation in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LinkedList | |
attr_accessor :list | |
def initialize | |
@list = [] | |
end | |
def add_node(data) | |
node = Struct.new(:data, :next) | |
new_node = node.new(data, nil) | |
list.last.next = new_node if list.last | |
list << new_node | |
end | |
def last | |
list.any? ? list.last : nil | |
end | |
def all | |
list | |
end | |
end | |
## Usage ## | |
# llist = LinkedList.new | |
# llist.add_node(2) | |
# llist.add_node(5) | |
# first_node = llist.all.first | |
# first_node.next.data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment