文章目录
题目
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
题解
1. 先找大于x的节点,然后进行插入
python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def partition(self, head, x):
"""
:type head: Optional[ListNode]
:type x: int
:rtype: Optional[ListNode]
"""
dummy = ListNode(next=head)
cur = dummy
left = dummy
right = None
while cur and cur.next:
if cur.next.val >= x:
left = cur
right = cur.next
break
cur = cur.next
cur = right
while cur and cur.next:
if cur.next.val < x:
tmp = cur.next
cur.next = cur.next.next
left.next = tmp
tmp.next = right
left = tmp
else:
cur = cur.next
return dummy.next
2. 小链表,大链表
python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def partition(self, head, x):
"""
:type head: Optional[ListNode]
:type x: int
:rtype: Optional[ListNode]
"""
small_dummy = ListNode(0)
big_dummy = ListNode(0)
small = small_dummy
big = big_dummy
while head:
if head.val < x:
small.next = head
small = small.next
else:
big.next = head
big = big.next
head = head.next
small.next = big_dummy.next
big.next = None
return small_dummy.next