Class: RubyCollections::LinkedList
- Inherits:
-
Object
- Object
- RubyCollections::LinkedList
- Defined in:
- lib/ruby_collections/linked_list.rb
Defined Under Namespace
Classes: Node
Instance Attribute Summary collapse
-
#size ⇒ Object
Returns the value of attribute size.
-
#top ⇒ Object
Returns the value of attribute top.
Instance Method Summary collapse
- #add(data, index = nil) ⇒ Object
- #empty? ⇒ Boolean
- #get(index) ⇒ Object
- #header ⇒ Object
-
#initialize ⇒ LinkedList
constructor
A new instance of LinkedList.
- #remove(index) ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize ⇒ LinkedList
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
#size ⇒ Object
Returns the value of attribute size.
3 4 5 |
# File 'lib/ruby_collections/linked_list.rb', line 3 def size @size end |
#top ⇒ Object
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
18 19 20 21 22 23 24 25 26 27 |
# File 'lib/ruby_collections/linked_list.rb', line 18 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
10 11 12 |
# File 'lib/ruby_collections/linked_list.rb', line 10 def empty? size.zero? end |
#get(index) ⇒ Object
29 30 31 32 33 |
# File 'lib/ruby_collections/linked_list.rb', line 29 def get(index) node = top index.times {node = node.getNext} return node end |
#header ⇒ Object
14 15 16 |
# File 'lib/ruby_collections/linked_list.rb', line 14 def header @top ? @top.to_s : nil end |
#remove(index) ⇒ Object
35 36 37 38 39 40 |
# File 'lib/ruby_collections/linked_list.rb', line 35 def remove(index) node = get(index-1) to_be_removed = node.getNext node.setNext(to_be_removed.getNext) @size -= 1 end |
#to_s ⇒ Object
42 43 44 45 46 47 48 |
# File 'lib/ruby_collections/linked_list.rb', line 42 def to_s return "" if empty? data = [] data << (node = top).data (size-1).times {data << (node = node.getNext).data} return data.to_s end |