Lintcode 599. Insert into a Cyclic Sorted List (Easy) (Python)

599. Insert into a Cyclic Sorted List

Description:

Given a node from a cyclic linked list which has been sorted, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be any single node in the list. Return the inserted new node.
Example
Given a list, and insert a value 4:
3->5->1
Return 5->1->3->4

Code:

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param: node: a list node in the list
    @param: x: An integer
    @return: the inserted new list node
    """
    def insert(self, node, x):
        # write your code 
        originNode = node
        tmp = ListNode(x)
        if node == None:
            node = tmp
            node.next = node
            return node
        else:
            while True:
                if node.next.next == node:
                    tmp.next = node.next
                    node.next = tmp
                    return node
                if (node.val<=x and node.next.val>x) or (node.val<x and node.next.val>=x) or (node.val>node.next.val and node.val<x and node.next.val<x) or (node.val>node.next.val and node.val>x and node.next.val>x):
                    tmp.next = node.next
                    node.next = tmp
                    return node
                node = node.next
                if node == originNode:
                    tmp.next = node.next
                    node.next = tmp
                    return node

猜你喜欢

转载自blog.csdn.net/weixin_41677877/article/details/81200818
今日推荐