Class: Alimento::List

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/alimento/list.rb

Overview

Lista doblemente enlazada y enumerable. Es posible inicializarla añadiéndole valores desde un principio.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*values) ⇒ List

Returns a new instance of List.



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

def initialize(*values)
  @head = Nodo.new(nil, nil, nil)
  @tail = @head
  if values != nil
    values.each { |value| unshift(value) }
  end
end

Instance Attribute Details

#headObject (readonly)

Returns the value of attribute head.



12
13
14
# File 'lib/alimento/list.rb', line 12

def head
  @head
end

#tailObject (readonly)

Returns the value of attribute tail.



12
13
14
# File 'lib/alimento/list.rb', line 12

def tail
  @tail
end

Instance Method Details

#<<(value) ⇒ Object



55
56
57
# File 'lib/alimento/list.rb', line 55

def <<(value)
  unshift(value)
end

#eachObject



76
77
78
79
80
81
82
# File 'lib/alimento/list.rb', line 76

def each
  aux = @head
  while (aux != nil)
    yield aux.value
    aux = aux.next
  end
end

#emptyObject

Devuelve un booleano indicando si la lista se encuentra vacía.



21
22
23
# File 'lib/alimento/list.rb', line 21

def empty
  @head.value == nil
end

#firstObject

Devuelve la cabeza de la lista



59
60
61
# File 'lib/alimento/list.rb', line 59

def first
  @head.value
end

#lastObject

Devuelve la cola de la lista



63
64
65
# File 'lib/alimento/list.rb', line 63

def last
  @tail.value
end

#sizeObject

Devuelve el número de elementos contenidos en la lista.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/alimento/list.rb', line 25

def size
  if empty
    0
  elsif head == tail && head.value != nil
    1
  else
    i = 1
    aux = @head
    while aux != @tail
      i += 1
      aux = aux.next
    end
    i
  end
end

#to_sObject



66
67
68
69
70
71
72
73
74
75
# File 'lib/alimento/list.rb', line 66

def to_s
  ret = "{"
  aux = @head
  while (aux != @tail) do
    ret += "#{aux.value.to_s}, "
    aux = aux.next
  end
  ret += "#{aux.value.to_s}}"
  return ret
end

#unshift(value) ⇒ Object

Inserta un elemento “value” al final de la lista



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

def unshift(value)
  if empty
    @head.value = value
  elsif size == 1
    @tail = Nodo.new(value, nil, @head)
    @head.next = @tail
  else
    aux = Nodo.new(@tail.value, nil, @tail.prev)
    pre_tail = @tail.prev
    @tail = Nodo.new(value, nil, aux)
    aux.next = @tail
    pre_tail.next = aux
  end
end