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

Returns a new instance of LinkedList.



5
6
7
8
# File 'lib/ruby_collections/linked_list.rb', line 5

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



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/ruby_collections/linked_list.rb', line 14

def add(data, index = nil)
  return nil if index and index >= size
  if index
    new_node = Node.new data, nil
    get(index-1).setNext(new_node)
  else
    node = Node.new(data, top)
    @top = node
  end
  @size += 1 
end

#get(index) ⇒ Object



26
27
28
29
30
# File 'lib/ruby_collections/linked_list.rb', line 26

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

#isEmpty?Boolean

Returns:

  • (Boolean)


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

def isEmpty?
  size.zero?
end

#remove(index) ⇒ Object



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

def remove(index)
  node = get(index-1)
  to_be_removed = node.getNext
  node.setNext(to_be_removed.getNext)
  @size -= 1
end

#to_sObject



39
40
41
42
43
44
# File 'lib/ruby_collections/linked_list.rb', line 39

def to_s
  data = []
  data << (node = top).data
  (size-1).times {data << (node = node.getNext).data}
  return data.to_s
end