-
题目链接 https://leetcode-cn.com/problems/partition-list/
-
题目描述
-
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
-
输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5
-
-
解题思路
- 维护两个链表,一个全部大等于于x,一个全部小于x,遍历原链表时,根据条件加入
-
代码
- python
class Solution: def partition(self, head: ListNode, x: int) -> ListNode: if not head or not head.next: return head l, r = ListNode('#'), ListNode('#') tmp1, tmp2 = l, r while head: tmp, head = head, head.next if tmp.val < x: tmp1.next = tmp tmp1 = tmp1.next else: tmp2.next = tmp tmp2 = tmp2.next tmp2.next = None r = r.next tmp1.next = r return l.next
- python
leetcode 86. 分隔链表
猜你喜欢
转载自blog.csdn.net/qq_38043440/article/details/89331975
今日推荐
周排行