Skip to content

Instantly share code, notes, and snippets.

@imouaddine
Created November 12, 2014 14:50
Show Gist options
  • Save imouaddine/4bce4cedf0c2c68c2410 to your computer and use it in GitHub Desktop.
Save imouaddine/4bce4cedf0c2c68c2410 to your computer and use it in GitHub Desktop.
Partition Linked List
class LinkedList
attr_accessor :head, :tail
class Node
attr_accessor :previous, :next, :value
def initialize(value)
@value = value
end
end
def inspect
current = head
while (current)
print current.value
print " >> "
current = current.next
end
end
def partition(value)
dummy_1 = Node.new(0)
dummy_2 = Node.new(0)
current_1 = dummy_1
current_2 = dummy_2
current = self.head
while current
_next = current.next
current.next = nil
if current.value < value
current_1.next = current
current_1 = current_1.next
else
current_2.next = current.clone
current_2 = current_2.next
end
current = _next
end
if dummy_1.next
self.head = dummy_1.next
current_1.next = dummy_2.next
else
self.head = dummy_2.next
end
self
end
end
l = LinkedList.new
l.head = node1 = LinkedList::Node.new(5)
node1.next = node2 = LinkedList::Node.new(3)
node2.previous = node1
node2.next = node3 = LinkedList::Node.new(1)
node3.previous = node2
node3.next = node4 = LinkedList::Node.new(6)
node4.previous = node3
l.partition(3).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment