-
Notifications
You must be signed in to change notification settings - Fork 21
/
doubly_linked_list.rb
69 lines (55 loc) · 1.23 KB
/
doubly_linked_list.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
require_relative 'node.rb'
class LinkedList
include Enumerable
attr_accessor :length
def initialize
@length = 0
@index = -1
end
def [](pos)
return if pos >= length || pos < 0 # bounds check
delta = pos > @index ? 1 : -1 # set direction
until @index == pos # traverse
@current = delta == 1 ? @current.next : @current.previous
@index += delta
end
@current.data
end
def []=(pos, data)
return if pos < 0 # bounds check
create_head if index == -1
delta = pos > @index ? 1 : -1 # set direction
until @index == pos # traverse
create_next_node if @index == @length - 1 # create missing nodes
@current = delta == 1 ? @current.next : @current.previous
@index += delta
end
@current.data = data
end
def <<(value)
self[@length] = value
end
def each
(0...@length).each do |x|
yield self[x]
end
end
def first
@head.data
end
def last
@tail.data
end
private
def create_head
@head = Node.new
@tail = @head
@index = 0
@length = 1
end
def create_next_node
@tail.next = Node.new
@tail = @tail.next
@length += 1
end
end