-
Notifications
You must be signed in to change notification settings - Fork 21
/
partition_linked_list.rb
66 lines (60 loc) · 1.98 KB
/
partition_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
# CtCI 6th Edition Problem 2.4
# Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
# before all nodes greater than or equal to x. lf x is contained within the list, the values of x only need
# to be after the elements less than x (see below). The partition element x can appear anywhere in the
# "right partition"; it does not need to appear between the left and right partitions.
# EXAMPLE
# Input: 3 -> 5 -> 8 -> 5 - > 10 -> 2 -> 1 [partition = 5)
# Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
class Node
attr_accessor :data, :next
def initialize(data)
@data = data
@next = nil
end
def to_s
data_str = ''
current = self
until current.nil?
data_str << "->#{current.data}"
current = current.next
end
data_str[2..data_str.size]
end
def to_a
@next.nil? ? [data] : [data] + @next.to_a
end
end
# Loops through all the nodes so it is O(n)
def partition_linked_list(head, partition)
# Plan is to have a left and right side. Go through the list and add the node to the left side or right side.
left_head = nil
left_tail = nil
right_head = nil
right_tail = nil
current_node = head
until current_node.nil?
if current_node.data < partition # Add to left partition
if left_head.nil? # Create left head and tail on the first run
left_head = current_node
left_tail = current_node
else # Add to the left tail
left_tail.next = current_node
left_tail = left_tail.next
end
else # Add to right partition
if right_head.nil? # Create right head and tail on the first run
right_head = current_node
right_tail = current_node
else # Add to the right tail
right_tail.next = current_node
right_tail = right_tail.next
end
end
current_node = current_node.next
end
# Attach the two partitions and return the left head
left_tail.next = right_head
right_tail.next = nil
left_head
end