Given the head
of 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 1:
Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2,4,3,5]
Example 2:
Input: head = [2,1], x = 2 Output: [1,2]
Constraints:
- The number of nodes in the list is in the range
[0, 200]
. -100 <= Node.val <= 100
-200 <= x <= 200
题目大意:给定一个链表和一个指定值x,要求把链表分成前后两部分,所有小于x的节点在前,所有大于等于x的节点在后,要求两个部分里的节点前后顺序要保持跟原链表一致。
解法比较容易想到,定义两个临时链表,遍历原链表,要是当前节点值小于x则把其放入第一个临时链表中,否则放入第二个临时链表。最后把第一个临时链表的结尾连到第二临时链表的开头,就实现了对原链表的分区。
注意点:两个临时链表的头节点是临时节点并不属于原链表,合并时要排除;第二个临时链表的尾节点就是新链表的尾节点,因此其next需要指向空节点。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
preHead1, preHead2 = ListNode(-1), ListNode(-1)
p1, p2 = preHead1, preHead2
cur = head
while cur:
if cur.val < x:
p1.next = cur
p1 = p1.next
else:
p2.next = cur
p2 = p2.next
cur = cur.next
p2.next = None
p1.next = preHead2.next
return preHead1.next