leetcode 86. 分隔链表

  1. 题目链接 https://leetcode-cn.com/problems/partition-list/

  2. 题目描述

    1. 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

      你应当保留两个分区中每个节点的初始相对位置。

    2. 输入: head = 1->4->3->2->5->2, x = 3
      输出: 1->2->2->4->3->5
  3. 解题思路

    1. 维护两个链表,一个全部大等于于x,一个全部小于x,遍历原链表时,根据条件加入
  4. 代码

    1. 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
      
      

猜你喜欢

转载自blog.csdn.net/qq_38043440/article/details/89331975