Class: ListaEnlazada

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/prct06/ListaEnlazada.rb

Overview

Clase que implementa una lista enlazada

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeListaEnlazada

Al inicializarse el objeto. El tamaño de la lista es cero y tanto @bottom como @top son nil.



14
15
16
17
18
# File 'lib/prct06/ListaEnlazada.rb', line 14

def initialize
  @bottom = nil
  @top = nil
  @size = 0
end

Instance Attribute Details

#bottomObject (readonly)

Returns the value of attribute bottom.



10
11
12
# File 'lib/prct06/ListaEnlazada.rb', line 10

def bottom
  @bottom
end

#sizeObject (readonly)

Returns the value of attribute size.



10
11
12
# File 'lib/prct06/ListaEnlazada.rb', line 10

def size
  @size
end

#topObject (readonly)

Returns the value of attribute top.



10
11
12
# File 'lib/prct06/ListaEnlazada.rb', line 10

def top
  @top
end

Instance Method Details

#eachObject



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

def each
  i = bottom
  while i!=nil do
    yield i.value
    i = i.next;
  end
end

#popObject

Elimina el último elemento añadido a la lista. En este caso, @top apuntará al elemento anterior.



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/prct06/ListaEnlazada.rb', line 37

def pop
  if @top==nil
    output = "Error. La lista está vacía."
  else
    @top = @top.previous
    if @top == nil
      @bottom = nil
    end
    @size -= 1
  end
end

#push(element) ⇒ Object

Añade un elemento al final de la lista. @top apuntará al último elemento añadido



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/prct06/ListaEnlazada.rb', line 21

def push (element)
  aux = @top
  @top = Node.new(element, nil ,@top)
  if (aux!=nil)
    aux.next = @top
  end
  if (@bottom != nil && @bottom.next == nil )
    @bottom.next = @top
  end
  if @bottom == nil
    @bottom = @top
  end
  @size += 1
end

#to_sObject

Método que permite mostrar el último elemento añadido en la lista. En caso de que la lista esté vacía, mostrará el mensaje “Error. La lista está vacía”



59
60
61
62
63
64
65
# File 'lib/prct06/ListaEnlazada.rb', line 59

def to_s
  if @top==nil
    output = "Error. La lista está vacía."
  else
    @top.value.to_s
  end
end