# Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or
# equal to x.
#
# You should preserve the original relative order of the nodes in each of the two partitions.
#
# For example,
# Given 1->4->3->2->5->2 and x = 3,
# return 1->2->2->4->3->5.

# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        less = None
        less_tail = None
        great = None
        great_tail = None

        p1 = head

        while p1:
            p2 = p1.next
            p1.next = None
            if p1.val < x:
                if not less:
                    less = p1
                else:
                    less_tail.next = p1
                less_tail = p1
            else:
                if not great:
                    great = p1
                else:
                    great_tail.next = p1
                great_tail = p1

            p1 = p2

        if less_tail:
            less_tail.next = great
            return less
        else:
            return great

# Note:
# We create two list for nums greater than or equal to x and another for less and merge it later on
