Class: List

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/Prct07/List.rb

Overview

Author:

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeList

Returns a new instance of List.



11
12
13
14
# File 'lib/Prct07/List.rb', line 11

def initialize
  @head = @tail = nil
  @size = 0
end

Instance Attribute Details

#sizeObject (readonly)

Returns the value of attribute size.



9
10
11
# File 'lib/Prct07/List.rb', line 9

def size
  @size
end

Instance Method Details

#backObject

returns the last element of the list



81
82
83
# File 'lib/Prct07/List.rb', line 81

def back
  @tail.value
end

#eachObject

necessary for enumerable module



104
105
106
107
108
109
110
# File 'lib/Prct07/List.rb', line 104

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

#emptyObject

checks if the list is empty



42
43
44
# File 'lib/Prct07/List.rb', line 42

def empty
  @size == 0
end

#frontObject

returns the first element of the list



86
87
88
# File 'lib/Prct07/List.rb', line 86

def front
  @head.value
end

#getAt(index) ⇒ Object

returns the element specificated by the index



91
92
93
94
95
96
97
98
99
100
101
# File 'lib/Prct07/List.rb', line 91

def getAt index
  if (index >= @size)
    nil
  else
    aux = @head
    for i in 0..index - 1
      aux = aux.next
    end
    aux.value
  end
end

#pop_backObject

extracts the last element of the list and returns it



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/Prct07/List.rb', line 64

def pop_back
  @size = @size - 1
  if (@head == nil)
    nil
  else
    aux = @tail
    if (@tail.prev != nil)
      @tail = @tail.prev
      @tail.next = nil
    else
      @head = nil
    end
    aux.value
  end
end

#pop_frontObject

extracts the first element of the list and returns it



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/Prct07/List.rb', line 47

def pop_front
  @size = @size - 1
  if (@head == nil)
    nil
  else
    aux = @head
    if (@head.next != nil)
      @head = @head.next
      @head.prev = nil
    else
      @head = nil
    end
    aux.value
  end
end

#push_back(element) ⇒ Object

inserts elements by the tail of the list



17
18
19
20
21
22
23
24
25
26
# File 'lib/Prct07/List.rb', line 17

def push_back element
  @size = @size + 1
  if (@head == nil)
    @head = @tail = Node.new element, nil, nil
  else
    @tail.next = Node.new element, @tail, nil
    @tail = @tail.next
  end
  true
end

#push_front(element) ⇒ Object

inserts elements by the head of list



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

def push_front element
  @size = @size + 1
  if (@head == nil)
    @head = @tail = Node.new element, nil, nil
  else
    aux = @head
    @head = Node.new element, nil, aux
    aux.prev = @head
  end
  true
end