zoukankan      html  css  js  c++  java
  • 【leetcode】86. Partition List

    题目如下:

    Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

    You should preserve the original relative order of the nodes in each of the two partitions.

    Example:

    Input: head = 1->4->3->2->5->2, x = 3
    Output: 1->2->2->4->3->5

    解题思路:我的方法和【leetcode】328. Odd Even Linked List 一样,使用less 和 great 两个指针,分别指向小于和等于或大于的节点,最后再把less的尾节点指向great的头结点即可。

    代码如下:

    # 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
            """
            lessHead = less = greatHead = great = None
            current = head
            while current != None:
                tmp = current.next
                current.next = None
                if current.val < x:
                    if lessHead == None:
                        lessHead = current
                        less = lessHead
                    else:
                        less.next = current
                        less = less.next
                else:
                    if greatHead == None:
                        greatHead = great = current
                    else:
                        great.next = current
                        great = great.next
                current = tmp
            if less != None:
                less.next = greatHead
            else:
                lessHead = greatHead
            return lessHead
  • 相关阅读:
    卡嘉mysql命令
    Go并发控制和超时控制
    sync包介绍
    Golang-RSA加密解密-数据无大小限制
    GO json 如何转化为 map 和 struct
    go之gorm
    go mod 生成 vendor
    go语言中找&和*区别
    Swoole的process通信的方式
    centos安装python3
  • 原文地址:https://www.cnblogs.com/seyjs/p/10194292.html
Copyright © 2011-2022 走看看