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                    

 

转载于:https://www.cnblogs.com/bozhou/p/6945210.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值