forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
doubly_linked_list.rb
86 lines (76 loc) · 1.64 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# frozen_string_literal: true
# Class to represent each node from the linked list
class Node
attr_accessor :data, :next, :previous
def initialize(data)
@data = data
@next = nil
@previous = nil
end
end
# Implement a doubly linked list
class DoublyLinkedList
def initialize
@head = nil
end
def append(data)
if @head.nil?
@head = Node.new(data)
else
tail_node = find_tail
new_node = Node.new(data)
tail_node.next = new_node
new_node.previous = tail_node
end
end
def find_tail
current_tail = @head
current_tail = current_tail.next until current_tail.next.nil?
current_tail
end
def delete(value)
if @head.data == value
@head = @head.next
@head.previous = nil
else
target = find(value)
if target.next.nil?
target.previous.next = nil
else
target.previous.next = target.next
target.next.previous = target.previous
end
end
end
def find(value)
current = @head
current = current.next until current.data == value
current
end
def insert_after(target, value)
current = find(target)
temp = current.next
current.next = Node.new(value)
current.next.next = temp
current.next.previous = current
current.next.next.previous = current.next
end
def print_list
current = @head
puts "List: "
until current.nil?
print "#{current.data} "
current = current.next
end
end
end
list = DoublyLinkedList.new
list.append(10)
list.append(20)
list.append(30)
list.insert_after(20, 22)
list.print_list
list.delete(30)
list.print_list
list.delete(10)
list.print_list