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                    
    
  • 相关阅读:
    Eclipse 远程调试
    大数据处理方法bloom filter
    sicily 1259 Sum of Consecutive Primes
    sicily 1240. Faulty Odometer
    sicily 1152 简单马周游 深度优先搜索及回溯算法
    sicily 1050 深度优先搜索解题
    sicily 1024 邻接矩阵与深度优先搜索解题
    sicily 1156 二叉树的遍历 前序遍历,递归,集合操作
    sicily 1443 队列基本操作
    sicily 1006 team rankings 枚举解题
  • 原文地址:https://www.cnblogs.com/bozhou/p/6945210.html
Copyright © 2011-2022 走看看