Class: Algorithmable::DataStructs::LinkedList::Singly

Inherits:
Base
  • Object
show all
Defined in:
lib/algorithmable/data_structs/linked_list/singly.rb

Instance Method Summary collapse

Instance Method Details

#delete(item) ⇒ Object


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/algorithmable/data_structs/linked_list/singly.rb', line 71

def delete(item)
  tmp_node = @front
  prev_node = nil

  until tmp_node.nil?
    if tmp_node.item == item
      if tmp_node == @front
        next_node = @front.next
        @back = next_node if @front == @back
        @front = next_node
        @size -= 1
      else
        prev_node.next = tmp_node.next
        @back = prev_node if tmp_node == @back
        @size -= 1
      end
      return true
    else
      prev_node = tmp_node
    end

    tmp_node = tmp_node.next
  end
end

#merge(other) ⇒ Object


96
97
98
99
100
101
102
103
104
# File 'lib/algorithmable/data_structs/linked_list/singly.rb', line 96

def merge(other)
  front = recursive_merge_imp self.front, other.front
  list = self.class.new
  while front
    list.push_back front.item
    front = front.next
  end
  list
end

#pop_backObject


56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/algorithmable/data_structs/linked_list/singly.rb', line 56

def pop_back
  return unless @back
  node = @back
  if @front == @back
    clear!
  else
    prev = @front
    prev = prev.next while prev.next != @back
    @back = prev
    @back.next = nil
    @size -= 1
  end
  node.item
end

#pop_frontObject


42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/algorithmable/data_structs/linked_list/singly.rb', line 42

def pop_front
  return unless @front
  node = @front

  if @front == @back
    clear!
  else
    @front = @front.next
    @size -= 1
  end

  node.item
end

#push_back(obj) ⇒ Object


29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/algorithmable/data_structs/linked_list/singly.rb', line 29

def push_back(obj)
  node = new_node(obj)
  if @back
    @back.next = node
    @back = node
  else
    @front = node
    @back = @front
  end
  @size += 1
  obj
end

#push_front(obj) ⇒ Object


16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/algorithmable/data_structs/linked_list/singly.rb', line 16

def push_front(obj)
  node = new_node(obj)
  if @front
    node.next = @front
    @front = node
  else
    @front = node
    @back = @front
  end
  @size += 1
  obj
end

#reverse!Object


106
107
108
109
110
# File 'lib/algorithmable/data_structs/linked_list/singly.rb', line 106

def reverse!
  @back = @front
  @front = reverse_imp @front
  self
end

#sort!Object


112
113
114
# File 'lib/algorithmable/data_structs/linked_list/singly.rb', line 112

def sort!
  sort_linked_list @front
end