给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5
方法一:转换列表,效率比较低
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
ptr = head
data = []
data1 = []
while ptr:
data.append(ptr.val)
ptr = ptr.next
for item in data:
if item < x:
data1.append(item)
for item in data1:
if item in data:
data.remove(item)
data1 = data1 + data
ptr2 = ListNode(0)
ptr3 = ptr2
for item in data1:
ptr2.next = ListNode(item)
ptr2 = ptr2.next
return ptr3.next
方法二:效率较高,但是空间复杂度较高
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
l1 = ListNode(0)
l2 = ListNode(0)
ptr1 = l1
ptr2 = l2
while head:
if head.val >= x:
l1.next = ListNode(head.val)
l1 = l1.next
else:
l2.next = ListNode(head.val)
l2 = l2.next
head = head.next
l2.next = ptr1.next
return ptr2.next