題目:給你一個鏈表的頭節點 head 和一個特定值 x ,請你對鏈表進行分隔,使得所有 小於 x 的節點都出現在 大於或等於 x 的節點之前。你應當 保留 兩個分區中每個節點的初始相對位置。
示例 1:
輸入:head = [1,4,3,2,5,2], x = 3 輸出:[1,2,2,4,3,5]
示例 2:輸入:head = [2,1], x = 2 輸出:[1,2]
提示:
鏈表中節點的數目在范圍 [0, 200] 內
-100 <= Node.val <= 100
-200 <= x <= 200
程序說明:
創建兩個啞節點,一個用於存儲比x小的數,一個存儲大於或等於x的數,後面再將兩鏈表合並即可。(建議畫圖理解)
全部代碼:
# 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: ListNode, x: int) -> ListNode:
p = ListNode(0)
small = p
q = ListNode(0)
big = q
while head:
if head.val<x:
small.next = head
small = small.next
else:
big.next = head
big = big.next
head = head.next
big.next = None
small.next = q.next
return p.next
題目來源:力扣(leetcode)