分类:LinkedList
考察知识点:LinkedList
最优解时间复杂度:**O(n) **
86. Partition List
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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
代码:
我的方法:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
if head == None:
return None
l1=ListNode(0)
p1=l1
l2=ListNode(0)
p2=l2
p=head
while p:
if p.val<x:
p1.next=p
p1=p1.next
else:
p2.next=p
p2=p2.next
p=p.next
p2.next=None
p1.next=l2.next
return l1.next
讨论:
1.这道题过于简单了吧