class RubyCollections::LinkedList

Attributes

size[RW]
top[RW]

Public Class Methods

new() click to toggle source

TODO: implement iterator TODO: implement to_a

# File lib/ruby_collections/linked_list.rb, line 8
def initialize
  @size = 0
  @top = nil
end

Public Instance Methods

add(data, index = nil) click to toggle source
# File lib/ruby_collections/linked_list.rb, line 21
def add(data, index = nil)
  return nil if index and index >= size
  if index
    get(index-1).setNext(data)
  else
    node = Node.new(data, top)
    @top = node
  end
  @size += 1 
end
empty?() click to toggle source
# File lib/ruby_collections/linked_list.rb, line 13
def empty?
  size.zero?
end
get(index) click to toggle source
# File lib/ruby_collections/linked_list.rb, line 32
def get(index)
  node = top
  index.times {node = node.getNext}
  return node
end
header() click to toggle source
# File lib/ruby_collections/linked_list.rb, line 17
def header
  @top ? @top.to_s : nil
end
remove(index) click to toggle source
# File lib/ruby_collections/linked_list.rb, line 38
def remove(index)
  node = get(index-1)
  to_be_removed = node.getNext
  node.setNext(to_be_removed.getNext)
  @size -= 1
end
to_s() click to toggle source
# File lib/ruby_collections/linked_list.rb, line 45
def to_s
  return "" if empty?
  data = []
  data << (node = top).data
  (size-1).times {data << (node = node.getNext).data}
  return data.to_s
end