1. 题目描述
86.分隔链表
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
2. 代码实现
执行用时 :16 ms, 在所有 Python 提交中击败了96.88%的用户
内存消耗 :12.9 MB, 在所有 Python 提交中击败了33.33%的用户
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
# before和after是用来创建两个列表的两个指针
# before_head和after_head用于保存两个列表的头部.
# 所有这些都是用创建的虚拟节点初始化的.
before = before_head = ListNode(0)
after = after_head = ListNode(0)
while head:
# 如果原始列表节点小于给定的x
# 将它分配给before列表
if head.val < x:
before.next = head
before = before.next
else:
# 如果原始列表节点大于或等于给定的x
# 将它分配给after列表。
after.next = head
after = after.next
# 在原始列表中继续
head = head.next
# “after”列表的最后一个节点也将是经过修改的列表的结束节点
after.next = None
# 一旦所有的节点都被正确地分配到两个列表中,
# 将它们组合成一个返回的列表。
before.next = after_head.next
return before_head.next