96. Partition List/86. Partition List
- 本题难度: Easy/Medium
- Topic: Linked List
Description
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
Example 1:
Input: list = null, x = 0
Output: null
Explanation:
The empty list Satisfy the conditions by itself.
Example 2:
Input: list = 1->4->3->2->5->2->null, x = 3
Output: 1->2->2->4->3->5->null
Explanation:
keep the original relative order of the nodes in each of the two partitions.
我的代码
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list
@param x: An integer
@return: A ListNode
"""
def partition(self, head, x):
# write your code here
if head is None:
return head
l1 = ListNode(0)
l2 = ListNode(0)
p1, p2 = l1, l2
while(head):
if head.val<x:
l1.next = head
l1 = l1.next
else:
l2.next = head
l2 = l2.next
head = head.next
l1.next = None#防止结尾为错误
l2.next = None
if p1.next is None: #注意是p1而不是l1
return p2.next
else:
l1.next = p2.next# 需要考虑p1.next is None的情况
return p1.next
思路
分成两个数组,最后合到一起
- null
2.head.next == null
- 时间复杂度 O(n)
- 出错
- 当出现xx.next =yyy的时候要考虑到xx.next是否存在
- 最后一个值可能小于x,但是因为是直接接head,所以可能会残余。所以最后需要加上结尾为null
- 当前位置和开头位置的表示搞混了