Class: Ds101::LinkedList::DoubleLinkedList

Inherits:
Object
  • Object
show all
Includes:
Common
Defined in:
lib/ds_101/linked_list/double_linked_list.rb

Defined Under Namespace

Classes: Node

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Common

#clear, #concat, #each, #find, #find_by, #to_a

Constructor Details

#initializeDoubleLinkedList

Returns a new instance of DoubleLinkedList.



20
21
22
23
24
# File 'lib/ds_101/linked_list/double_linked_list.rb', line 20

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

Instance Attribute Details

#headObject (readonly)

Returns the value of attribute head.



8
9
10
# File 'lib/ds_101/linked_list/double_linked_list.rb', line 8

def head
  @head
end

#lengthObject (readonly)

Returns the value of attribute length.



8
9
10
# File 'lib/ds_101/linked_list/double_linked_list.rb', line 8

def length
  @length
end

#tailObject (readonly)

Returns the value of attribute tail.



8
9
10
# File 'lib/ds_101/linked_list/double_linked_list.rb', line 8

def tail
  @tail
end

Class Method Details

.init_from_arr(arr) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/ds_101/linked_list/double_linked_list.rb', line 26

def self.init_from_arr(arr)
  list = DoubleLinkedList.new
  arr.each do |value|
    list.append(value)
  end
  list
end

Instance Method Details

#append(value) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/ds_101/linked_list/double_linked_list.rb', line 34

def append(value)
  node = Node.new(value: value)
  if head.nil?
    @head = node
  else
    tail.next = node
    node.prev = tail
  end
  @tail = node
  @length += 1
  node
end

#remove(value) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/ds_101/linked_list/double_linked_list.rb', line 47

def remove(value)
  return unless head
  return remove_head if head.value == value

  current = head
  current = current.next while current&.next && current.next.value != value
  return unless current&.next

  if current.next == tail
    @tail = current
    @tail.next = nil
  else
    current.next = current.next.next
    current.next.prev = current
  end
  @length -= 1
end

#remove_headObject



65
66
67
68
69
70
71
72
73
74
# File 'lib/ds_101/linked_list/double_linked_list.rb', line 65

def remove_head
  if head.next.nil?
    @head = nil
    @tail = nil
  else
    head.next.prev = nil
    @head = head.next
  end
  @length -= 1
end