Skip to content

Instantly share code, notes, and snippets.

@imouaddine
Created November 8, 2014 16:15
Show Gist options
  • Save imouaddine/c870be92c30a80535aff to your computer and use it in GitHub Desktop.
Save imouaddine/c870be92c30a80535aff to your computer and use it in GitHub Desktop.
Merge two 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 merge(other)
if head == nil
self.head = other.head
return
end
fake_head = Node.new(0)
current_fake = fake_head
current_1 = self.head
current_2 = other.head
while (current_1 && current_2)
if current_1.value <= current_2.value
current_fake.next = current_1
current_1 = current_1.next
else
current_fake.next = current_2
current_2 = current_2.next
end
current_fake = current_fake.next
end
if current_2
current_fake.next = current_2
end
if current_1
current_fake.next = current_1
end
self.head = fake_head.next
self
end
def reverse
current = head
while (current)
_next = current.next
current.next = current.previous
current.previous = _next
current = current.previous
end
_tmp = head
self.head = tail
self.tail = _tmp
end
end
l = LinkedList.new
l.head = node1 = LinkedList::Node.new(1)
node1.next = node2 = LinkedList::Node.new(3)
node2.previous = node1
node2.next = node3 = LinkedList::Node.new(5)
node3.previous = node2
node3.next = node4 = LinkedList::Node.new(6)
node4.previous = node3
other = LinkedList.new
other.head = node1 = LinkedList::Node.new(2)
node1.next = node2 = LinkedList::Node.new(6)
node2.next = node3 = LinkedList::Node.new(11)
node3.next = LinkedList::Node.new(14)
l.merge(other)
puts l.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment