partition List Leetcode Python




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 .
アルゴリズム複雑度O(n)
チェーンテーブルを1回巡って、X未満の値を1番目のチェーンテーブルに順次加算し、X以上の値を2番目のチェーンテーブルに加算します.遍歴が終わったら、最初のチェーンテーブルのしっぽを第2のチェーンテーブルの頭に向けます.
最初のチェーンテーブルのヘッダを返します.
The time complexity is O(n), we need to go through the whole linklist and compare the tmp value with x. If the tmp value is smaller than X, we append it to the first linklist otherwise the second. Then append the head of the second linklist to the tail of the first linklist. Return the head of the first linklist.
I was also thing about just swap positions in the linklist but have no idea right now. If anyone have it please do not hesitate to leave me some message.
Below is the code:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @param x, an integer
    # @return a ListNode
    def partition(self, head, x):
        dummy=ListNode(0)
        dummy.next=head
        dummy1=ListNode(0)
        dummy2=ListNode(0)
        head1=dummy1
        head2=dummy2
        tmp=head
        while tmp:
            if tmp.val<x:
                head1.next=tmp
                tmp=tmp.next
                head1=head1.next
                head1.next=None
            else:
                head2.next=tmp
                tmp=tmp.next
                head2=head2.next
                head2.next=None
        head1.next=dummy2.next
        head=dummy1.next
        return head