# 分隔链表

给你一个链表的头节点 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]

 

提示:

## template ```python class ListNode(object): def __init__(self, x): self.val = x self.next = None class LinkList: def __init__(self): self.head=None def initList(self, data): self.head = ListNode(data[0]) r=self.head p = self.head for i in data[1:]: node = ListNode(i) p.next = node p = p.next return r def convert_list(self,head): ret = [] if head == None: return node = head while node != None: ret.append(node.val) node = node.next return ret class Solution(object): def partition(self, head, x): """ :type head: ListNode :type x: int :rtype: ListNode """ if head is None: return None less = lesshead = None last = pos = head while pos is not None: if pos.val < x: if lesshead is None: lesshead = pos else: less.next = pos less = pos if head == pos: last = head = pos.next else: last.next = pos.next else: last = pos pos = pos.next if lesshead is not None: less.next = head else: lesshead = head return lesshead # %% l = LinkList() list1 = [1,4,3,2,5,2] l1 = l.initList(list1) x = 3 s = Solution() print(l.convert_list(s.partition(l1, x))) ``` ## 答案 ```python ``` ## 选项 ### A ```python ``` ### B ```python ``` ### C ```python ```