zoukankan      html  css  js  c++  java
  • 86. 分隔链表



    思路:

    1、遍历原链表,分别找到小于x的节点与大于等于x的节点组成的两个链表small和big;

    2、拼接small和big,small在前。

    class Solution(object):
        def partition(self, head, x):
            """
            :type head: ListNode
            :type x: int
            :rtype: ListNode
            """
            if not head:
                return head
            # 小于x的节点,ans.next是返回值
            small = ans = ListNode(-1)
            # 不小于x的节点
            big = head_big = ListNode(-1)
            # 遍历指针
            cur = head
            while cur:
                if cur.val < x:
                    small.next = cur
                    small = small.next
                else:
                    big.next = cur
                    big = big.next
                cur = cur.next
            # 将两个链表段拼接,小于x的在前,不小于x的在后
            big.next = None
            small.next = head_big.next
            return ans.next
    
  • 相关阅读:
    LeetCode
    LeetCode
    LeetCode
    深度学习笔记 (二) 在TensorFlow上训练一个多层卷积神经网络
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12900073.html
Copyright © 2011-2022 走看看