86. 分隔链表
给你一个链表和一个特定值 x ,请你对链表进行分隔,使得所有小于 x 的节点都出现在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
思路:遍历
注意事项:链表题,一定一定自己画一下图,不然很容易出错
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
a,b = ListNode(0),ListNode(0)
cura,curb = a,b
while(head):
if head.val<x:
cura.next = head
cura = cura.next
else:
curb.next = head
curb = curb.next
head = head.next
curb.next = None
cura.next = b.next
return a.next