Class: Dll

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDll

Initializes to an empty list



13
14
15
16
# File 'lib/TDD/Dll.rb', line 13

def initialize
    @head = nil
    @tail = nil
end

Instance Attribute Details

#headDllNode (readonly)

Getter for the head node

Returns:

  • (DllNode)

    The first node on the list or nil if there is none



6
7
8
# File 'lib/TDD/Dll.rb', line 6

def head
  @head
end

#tailDllNode (readonly)

Getter for the tail node

Returns:

  • (DllNode)

    The last node on the list or nil if there is none



10
11
12
# File 'lib/TDD/Dll.rb', line 10

def tail
  @tail
end

Instance Method Details

#eachObject

Iterates over the list and yields for each item. The yield passes the value of each element to the block



73
74
75
76
77
78
79
# File 'lib/TDD/Dll.rb', line 73

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

#extract_headObject

Deletes the first element on the list



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/TDD/Dll.rb', line 45

def extract_head
    if( @head != nil )
        if( @head.next == nil )
            @head = nil
            @tail = nil
        else
            @head = @head.next
            @head.prev.next = nil
            @head.prev = nil
        end
    end
end

#extract_tailObject

Deletes the last element on the list



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/TDD/Dll.rb', line 59

def extract_tail
    if( @tail != nil )
        if( @tail.prev == nil)
            @tail = nil
            @head = nil
        else
            @tail = @tail.prev
            @tail.next.prev = nil
            @tail.next = nil
        end
    end
end

#insert_head(value) ⇒ Object

Insert a new value, having it be the first on the list

Parameters:

  • value

    What you want to be inserted to the list



20
21
22
23
24
25
26
27
28
29
# File 'lib/TDD/Dll.rb', line 20

def insert_head(value)
    if( @head == nil )
        @head = DllNode.new( nil, value, nil )
        @tail = @head
    else
       aux = DllNode.new( nil, value, @head )
       @head.prev = aux
       @head = aux
    end
end

#insert_tail(value) ⇒ Object

Insert a new value, having it be the last on the list

Parameters:

  • value

    What you want to be inserted to the list



33
34
35
36
37
38
39
40
41
42
# File 'lib/TDD/Dll.rb', line 33

def insert_tail(value)
    if( @tail == nil )
        @head = DllNode.new( nil, value, nil )
        @tail = @head
    else
       aux = DllNode.new( @tail, value, nil )
       @tail.next = aux
       @tail = aux
    end
end