-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.rb
126 lines (113 loc) · 2.36 KB
/
LinkedList.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
class LLNode
attr_accessor :next, :item
def initialize item
@item = item
@next = nil
end
end
##
# A singly linked list with head and tail pointers
class LinkedList
attr_accessor :size
##
#initializes the list with size 0 and no head or tail
def initialize
@size = 0
@head = nil
@tail = nil
end
##
# Returns the first item in the list
def first
return @head.item
end
##
# Returns the last item in the list
def last
return @tail.item
end
def toArray
ret = Array.new @size
on = 0
node = @head
while node
ret[on] = node.item
node = node.next
on += 1
end
return ret
end
##
# Adds an item to the front of the list in O(1)
def addToFront item
#if list is empty
addHelper item do |i|
node = LLNode.new i
node.next = @head
@head = node
end
end
##
# Adds an item to the back of the list in O(1)
def addToBack item
addHelper item do |i|
node = LLNode.new i
@tail.next = node
@tail = node
end
end
def removeFromFront
if @head
@head = head.next
if size == 1
@tail = nil
end
size -= 1
end
end
def removeFromBack
if @head
if size == 1
@head = nil
@tail = nil
else
node = @head
while node.next != @tail
node = node.next
end
@tail = node
@tail.next = nil
@size -= 1
end
end
end
##
# Returns whether an item is in the list
def contains? item
node = @head
while node
if node.item == item
return true
end
node = node.next
return false
end
end
private
def addHelper item
if !@head
node = LLNode.new item
@head = node
@tail = node
else
yield item
end
@size += 1
end
end
list = LinkedList.new
list.addToBack 1
list.addToBack 2
list.removeFromBack
list.removeFromBack
puts list.toArray