Class: DataStructures101::LinkedList

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

Defined Under Namespace

Classes: Node

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*values) ⇒ LinkedList

Returns a new instance of LinkedList.



22
23
24
25
26
27
28
29
# File 'lib/data_structures_101/linked_list.rb', line 22

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)

Returns the value of attribute size.



20
21
22
# File 'lib/data_structures_101/linked_list.rb', line 20

def size
  @size
end

Instance Method Details

#<<(value) ⇒ Object



31
32
33
# File 'lib/data_structures_101/linked_list.rb', line 31

def <<(value)
  push(value)
end

#delete(value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/data_structures_101/linked_list.rb', line 35

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

#each(&block) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/data_structures_101/linked_list.rb', line 49

def each(&block)
  curr = head.next
  until curr.nil?
    block.call(value)
    curr = curr.next
  end
end

#fetch(index) ⇒ Object



57
58
59
# File 'lib/data_structures_101/linked_list.rb', line 57

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

#first(n = nil) ⇒ Object

Raises:

  • (ArgumentError)


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

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

  raise ArgumentError, "negative array size" if n < 0

  return new_list_from_range(0, n - 1)
end

#insert(index, *values) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/data_structures_101/linked_list.rb', line 61

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

  curr = index < 0 ? curr : curr.prev

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

#last(n = nil) ⇒ Object

Raises:

  • (ArgumentError)


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

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

  raise ArgumentError, "negative array size" if n < 0

  return new_list_from_range(size - n, size - 1)
end

#push(*values) ⇒ Object



88
89
90
91
92
93
# File 'lib/data_structures_101/linked_list.rb', line 88

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