Skip to content

Instantly share code, notes, and snippets.

@bparanj
Last active August 24, 2020 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bparanj/a855a644875336e52f5cbfd752f52fd0 to your computer and use it in GitHub Desktop.
Save bparanj/a855a644875336e52f5cbfd752f52fd0 to your computer and use it in GitHub Desktop.
# Definition for singly-linked list. https://leetcode.com/problems/partition-list/submissions/
# class ListNode
# attr_accessor :val, :next
# def initialize(val = 0, _next = nil)
# @val = val
# @next = _next
# end
# end
# @param {ListNode} head
# @param {Integer} x
# @return {ListNode}
def partition(head, x)
list = ListNode.new
first = list
list2 = ListNode.new
second = list2
current = head
while current
if current.val < x
first.next = ListNode.new(current.val)
first = first.next
else
second.next = ListNode.new(current.val)
second = second.next
end
current = current.next
end
current = list
while current.next
current = current.next
end
current.next = list2.next
return list.next
end
@bparanj
Copy link
Author

bparanj commented Aug 24, 2020

Refactored code:

# Definition for singly-linked list.
# class ListNode
#     attr_accessor :val, :next
#     def initialize(val = 0, _next = nil)
#         @val = val
#         @next = _next
#     end
# end
# @param {ListNode} head
# @param {Integer} x
# @return {ListNode}
def partition(head, x)
    list = ListNode.new
    first = list
    
    list2 = ListNode.new
    second = list2
    
    current = head
    
    while current
       if current.val < x
          first.next = ListNode.new(current.val)
          first = first.next
       else
           second.next = ListNode.new(current.val)
           second = second.next
       end
        current = current.next
    end
    
    first.next = list2.next
    
    return list.next
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment