链表分割

题目描述
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前

给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。

Solution:

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Partition:
    def partition(self, pHead, x):
        p1,p2 = [],[]
        while pHead is not None:
            if pHead.val<x:
                p1.append(pHead.val)
            else:
                p2.append(pHead.val)
            pHead = pHead.next
        pre = ListNode(0)
        work = pre
        for i in p1+p2:
            work.next = ListNode(i)
            work = work.next
        return pre.next

再贴一个会超时的解,然鹅谁特么能告诉这为什么会超时

class Partition:
    def partition(self, pHead, x):
        p1,p2 = [],[]
        while pHead is not None:
            if pHead.val<x:
                p1.append(pHead)
            else:
                p2.append(pHead)
            pHead = pHead.next
        pre = ListNode(0)
        work = pre
        for i in p1+p2:
            work.next = i
            work = work.next
        return pre.next
posted @ 2019-07-12 21:50  bernieloveslife  阅读(156)  评论(1编辑  收藏  举报