LintCode Python 简单级题目 96.链表划分

原题描述:

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

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

您在真实的面试中是否遇到过这个题?

Yes

样例

给定链表 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