Last active
May 25, 2016 13:43
-
-
Save andrebras/16d7dc7272bbaa40a47d6cf9c3be52e0 to your computer and use it in GitHub Desktop.
Linked List Sample
This file contains 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
# Joana: sample of a linked list in ruby, this was a first attempt and should (must :) be refactored! | |
class Node | |
attr_accessor :data, :next_node | |
def initialize(data, next_node = nil) | |
@data = data | |
@next_node = next_node | |
end | |
end | |
class LinkedList | |
attr_reader :size | |
def initialize | |
@head = nil | |
@size = 0 | |
end | |
def add(data) | |
return nil unless data | |
node = Node.new(data) | |
if @head.nil? | |
@head = node | |
else | |
iterator = node_at(@size - 1) | |
iterator.next_node = node | |
end | |
@size += 1 | |
end | |
def index(data) | |
return nil unless data | |
iterator = @head | |
(0..@size - 1).each do |i| | |
return i if iterator.data && iterator.data == data | |
iterator = iterator.next_node | |
end | |
nil | |
end | |
def get(index) | |
return nil unless index >= 0 | |
return nil unless index < @size | |
iterator = @head | |
(0..@size - 1).each do |i| | |
return iterator.data if i == index | |
iterator = iterator.next_node | |
end | |
nil | |
end | |
def remove(index) | |
return nil unless index | |
return nil if index < 0 | |
return nil if index > @size - 1 | |
node = node_at(index) | |
previous_node = node_at(index - 1) unless index == 0 | |
# head | |
if index == 0 | |
@head = node.next_node | |
# tail | |
elsif index == @size - 1 | |
previous_node.next_node = nil | |
# other | |
else | |
previous_node.next_node = node.next_node | |
end | |
node.next_node = nil | |
node.data = nil | |
@size -= 1 | |
end | |
private | |
def node_at(index) | |
iterator = @head | |
(0..@size - 1).each do |i| | |
return iterator if i == index | |
if iterator.next_node | |
iterator = iterator.next_node | |
end | |
end | |
nil | |
end | |
## More efficient way to find last node than LinkedList#node_at(index) | |
# def last_node | |
# iterator = @head | |
# | |
# while iterator.next_node | |
# iterator = iterator.next_node | |
# end | |
# | |
# iterator | |
# end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment