Class: RubyCollections::LinkedList

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_collections/linked_list.rb

Defined Under Namespace

Classes: Node

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLinkedList

TODO: implement iterator TODO: implement to_a



8
9
10
11
# File 'lib/ruby_collections/linked_list.rb', line 8

def initialize
  @size = 0
  @top = nil
end

Instance Attribute Details

#sizeObject

Returns the value of attribute size.



3
4
5
# File 'lib/ruby_collections/linked_list.rb', line 3

def size
  @size
end

#topObject

Returns the value of attribute top.



3
4
5
# File 'lib/ruby_collections/linked_list.rb', line 3

def top
  @top
end

Instance Method Details

#add(data, index = nil) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# 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?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/ruby_collections/linked_list.rb', line 13

def empty?
  size.zero?
end

#get(index) ⇒ Object



32
33
34
35
36
# File 'lib/ruby_collections/linked_list.rb', line 32

def get(index)
  node = top
  index.times {node = node.getNext}
  return node
end

#headerObject



17
18
19
# File 'lib/ruby_collections/linked_list.rb', line 17

def header
  @top ? @top.to_s : nil
end

#remove(index) ⇒ Object



38
39
40
41
42
43
# 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_sObject



45
46
47
48
49
50
51
# 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