Class: CircularLinked::List

Inherits:
Object
  • Object
show all
Defined in:
lib/circular_linked/list.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*values) ⇒ List



6
7
8
9
10
# File 'lib/circular_linked/list.rb', line 6

def initialize(*values)
  nodes = values.map {|v| Node.new(v) }
  @head = nodes.first
  nodes.each_with_index {|node, i| node.next = nodes[i+1] || @head }
end

Instance Attribute Details

#headObject

Returns the value of attribute head.



4
5
6
# File 'lib/circular_linked/list.rb', line 4

def head
  @head
end

Instance Method Details

#add(value) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/circular_linked/list.rb', line 12

def add(value)
  new_node = Node.new(value, head)
  
  @head ||= new_node
  new_node.next ||= head
  
  last_node.next = new_node
end

#eachObject



73
74
75
76
77
78
79
80
81
82
# File 'lib/circular_linked/list.rb', line 73

def each
  return unless head 
  
  node = head
  loop do
    yield(node)
    node = node.next
    break if node == head        
  end
end

#find(value) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/circular_linked/list.rb', line 29

def find(value)
  return nil unless head
  
  node = head
  while node.value != value
    node = node.next
    return nil if node == head
  end
  
  node
end

#items_valueObject



57
58
59
60
61
62
63
# File 'lib/circular_linked/list.rb', line 57

def items_value
  values = []
  return values unless head
  
  each {|node| values.push(node.value) }
  values
end

#last_nodeObject



21
22
23
24
25
26
27
# File 'lib/circular_linked/list.rb', line 21

def last_node
  return nil unless head
  
  node = head
  node = node.next while node.next != head
  node
end

#lengthObject



65
66
67
68
69
70
71
# File 'lib/circular_linked/list.rb', line 65

def length
  length = 0
  return length unless head
  
  each { length += 1 }
  length
end

#remove(value) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/circular_linked/list.rb', line 41

def remove(value)
  node = find(value)
  return unless node
  
  if head.next == head
    @head = nil
    return
  end
  
  node_before = head
  node_before = node_before.next while node_before.next != node
  node_before.next = node.next
  
  @head = node.next if node == head
end