Class: DataStructures101::LinkedList

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/data_structures_101/linked_list.rb

Overview

Author:

  • Rene Hernandez

Since:

  • 0.1

Defined Under Namespace

Classes: Node

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*values) ⇒ LinkedList

Returns a new instance of LinkedList.

Since:

  • 0.1



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

def initialize(*values)
  @size = 0
  @head = Node.new(nil)
  @tail = Node.new(nil, @head)
  @head.next = @tail

  push(*values)
end

Instance Attribute Details

#sizeObject (readonly)

Since:

  • 0.1



28
29
30
# File 'lib/data_structures_101/linked_list.rb', line 28

def size
  @size
end

Instance Method Details

#<<(value) ⇒ Object

Since:

  • 0.1



39
40
41
# File 'lib/data_structures_101/linked_list.rb', line 39

def <<(value)
  push(value)
end

#delete(value) ⇒ Object

Since:

  • 0.1



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/data_structures_101/linked_list.rb', line 43

def delete(value)
  curr = @head.next
  return_value = nil
  until curr == @tail
    if curr.value == value
      remove_node(curr)
      return_value = curr.value
    end
    curr = curr.next
  end

  return_value
end

#eachObject

Since:

  • 0.1



57
58
59
60
61
62
63
64
65
# File 'lib/data_structures_101/linked_list.rb', line 57

def each
  return enum_for(:each) unless block_given?

  curr = head.next
  until curr.nil?
    yield curr.value
    curr = curr.next
  end
end

#fetch(index) ⇒ Object

Since:

  • 0.1



67
68
69
# File 'lib/data_structures_101/linked_list.rb', line 67

def fetch(index)
  fetch_node(index).value
end

#first(n = nil) ⇒ Object

Raises:

  • (ArgumentError)

Since:

  • 0.1



82
83
84
85
86
87
88
# File 'lib/data_structures_101/linked_list.rb', line 82

def first(n = nil)
  return @head.next.value if n.nil?

  raise ArgumentError, 'negative array size' if n.negative?

  new_list_from_range(0, n - 1)
end

#insert(index, *values) ⇒ Object

Since:

  • 0.1



71
72
73
74
75
76
77
78
79
80
# File 'lib/data_structures_101/linked_list.rb', line 71

def insert(index, *values)
  curr = fetch_node(index)

  curr = index.negative? ? curr : curr.prev

  values.each do |value|
    curr = add_node(value, curr.next)
  end
  self
end

#last(n = nil) ⇒ Object

Raises:

  • (ArgumentError)

Since:

  • 0.1



90
91
92
93
94
95
96
# File 'lib/data_structures_101/linked_list.rb', line 90

def last(n = nil)
  return @tail.prev.value if n.nil?

  raise ArgumentError, 'negative array size' if n.negative?

  new_list_from_range(size - n, size - 1)
end

#push(*values) ⇒ Object

Since:

  • 0.1



98
99
100
101
102
103
# File 'lib/data_structures_101/linked_list.rb', line 98

def push(*values)
  values.each do |value|
    add_node(value, @tail)
  end
  self # Allows to concatenate consecutive calls to push
end