• 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                    
    
  • 相关阅读:
    抓取当前界面上任意控件图像的C#代码
    Visual Studio 2005各版本之间的区别
    CSDN上一个问题的回答
    RichTextBox的线程安全问题
    2005年LOGO设计趋势
    VB中的奇怪错误
    吴裕雄天生自然SPRINGSpring MVC的基本配置
    吴裕雄天生自然SPRING基于Java配置的Spring MVC应用
    吴裕雄天生自然SPRINGJSON数据交互
    吴裕雄天生自然SPRING基于注解的控制器
  • 原文地址:https://www.cnblogs.com/bozhou/p/6945210.html
Copyright © 2020-2023  润新知