zoukankan      html  css  js  c++  java
  • LintCode Python 简单级题目 96.链表划分

    原题描述:

    给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。

    你应该保留两部分内链表节点原有的相对顺序。

    样例

    给定链表 1->4->3->2->5->2->null,并且 x=3

    返回 1->2->2->4->3->5->null

    题目分析:

    添加两个指针,分别指向第一个大于等于X的第一个节点和小于X的第一个节点,

    实际情况就是第N个节点大于等于X时,N-1个节点必然就是小于X;

    由于可能节点第一个值就大于X,此时不存在N-1个节点,所以在原链表前新增一个节点,用于初始化链表循环。

    此时算法复杂度O(n)。

    """
    Definition of ListNode
    class ListNode(object):
    
        def __init__(self, val, next=None):
            self.val = val
            self.next = next
    """
    class Solution:
        """
        @param head: The first node of linked list.
        @param x: an integer
        @return: a ListNode
        """
        def partition(self, head, x):
            # write your code here
            if head is None or head.next is None: 
                return head
            node = ListNode(-999999)
            node.next = head
            head = node
            
            follow  = head
            pre = head
            # 找到第一个值大于x的节点
            while follow is not None and follow.val < x:
                pre = follow
                follow = follow.next
            # 所有节点都小于x,直接返回原head
            if follow is None: return head.next
            # 遍历链表,此时pre是follow的上一个节点
            while follow.next is not None:
                if follow.next.val < x:
                    # 删除原节点
                    other = follow.next
                    follow.next = follow.next.next
                    # 将其值插入到pre之后
                    tmp = pre.next
                    other.next = tmp
                    pre.next = other
                    pre = pre.next
                    continue
                follow = follow.next
            return head.next                    
    
  • 相关阅读:
    Can't remove netstandard folder from output path (.net standard)
    website项目的reference问题
    The type exists in both DLLs
    git常用配置
    Map dependencies with code maps
    How to check HTML version of any website
    Bootstrap UI 编辑器
    网上职位要求对照
    Use of implicitly declared global variable
    ResolveUrl in external JavaScript file in asp.net project
  • 原文地址:https://www.cnblogs.com/bozhou/p/6945210.html
Copyright © 2011-2022 走看看