Class: List

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

Overview

This class is used to represent double-linked lists It includes the mixin Enumerable

Defined Under Namespace

Classes: Node

Instance Method Summary collapse

Constructor Details

#initializeList

initializes the vales of the list’s head and tail to nil



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

def initialize

  @head = nil
  @tail = nil

end

Instance Method Details

#add(value) ⇒ Object

adds a value to the end of the list, behind the former last element if it’s the first element, this becomes the new head and tail



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/list.rb', line 31

def add (value)

  if @tail == nil then
    @head = Node.new(value, nil, nil)
    @tail = @head
  else
    temp = Node.new(value, nil, @tail)
    @tail.next = temp
    @tail = temp
  end

end

#addAll(array) ⇒ Object

adds all elements in the given Array to our list. This works by calling the add(value)-method for each element in the array



46
47
48
49
50
# File 'lib/list.rb', line 46

def addAll (array)

  array.each { |value| add(value) }

end

#eachObject

this method is included because we implement the method Enumerable. Yields every element in the list, one after another, by calling the to_a-method.



95
96
97
# File 'lib/list.rb', line 95

def each
  self.to_a.each { |i| yield i }
end

#getNodeObject

returns the head-node



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

def getNode

  @head

end

#headObject

returns the value of the head



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

def head
  @head.value
end

#isEmpty?Boolean

returns true if the list is empty and false else

Returns:

  • (Boolean)


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

def isEmpty?
  if @head == nil then
    true
  else
    false
  end
end

#tailObject

returns the value of the tail



65
66
67
# File 'lib/list.rb', line 65

def tail   
  @tail.value
end

#to_aObject

returns an array with all the values of this list



70
71
72
73
74
75
76
77
78
# File 'lib/list.rb', line 70

def to_a
  tempArray = []
  tempNode = @head
  while tempNode != nil do
    tempArray.push(tempNode.value)
    tempNode = tempNode.next
  end
  tempArray
end

#to_a_reverseObject

returns an array with all the values of this list, but in a reverse order



82
83
84
85
86
87
88
89
90
# File 'lib/list.rb', line 82

def to_a_reverse
  tempArray = []
  tempNode = @tail
  while tempNode != nil do
    tempArray.push(tempNode.value)
    tempNode = tempNode.prev
  end
  tempArray
end