partition List Leetcode Python

来源:互联网 发布:四小票采集软件 编辑:程序博客网 时间:2024/06/05 02:19

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)

遍历一遍链表依次把小于X的值加到第一个链表后,大于等于X的加到第二个链表后。遍历完毕后再把第一个链表的尾巴指向第二链表的头。

返回第一个链表的头。

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 = Noneclass 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


0 0
原创粉丝点击