• 219. 在排序链表中插入一个节点


    219. 在排序链表中插入一个节点

    中文English

    在链表中插入一个节点。

    样例

    样例 1:

    输入:head = 1->4->6->8->null, val = 5
    输出:1->4->5->6->8->null
    

    样例 2:

    输入:head = 1->null, val = 2
    输出:1->2->null
    第一个版本:
    """
    Definition of ListNode
    class ListNode(object):
        def __init__(self, val, next=None):
            self.val = val
            self.next = next
    """
    
    class Solution:
        """
        @param head: The head of linked list.
        @param val: An integer.
        @return: The head of new linked list.
        """
        def insertNode(self, head, val):
            # write your code here
            new_node = ListNode(val)
            #边界情况
            if not head: return None
            if head.val >= val: 
                new_node.next = head 
                return new_node
            
            p = head
            
            while p.next:
                #如果在中间的话,则直接返回
                if val > p.val and val <= p.next.val:
                    new_node.next = p.next
                    p.next = new_node
                    return head
                else:
                    p = p.next 
            else:
                #如果不在中间
                p.next = new_node
            
            return head 
            

    第二个版本:

    """
    Definition of ListNode
    class ListNode(object):
        def __init__(self, val, next=None):
            self.val = val
            self.next = next
    """
    
    class Solution:
        """
        @param head: The head of linked list.
        @param val: An integer.
        @return: The head of new linked list.
        """
        def insertNode(self, head, val):
            # write your code here
            #一直到val < p.next.val 的时候退出
            dummy = ListNode(0)
            dummy.next = head 
            
            p = dummy 
            while p.next  and val < p.next.val:
                p = p.next
            
            #开始拼接
            new_node = ListNode(val, p.next)
            p.next = new_node
            
            return head 
     
  • 相关阅读:
    更改eclipse(myeclipse) author的默认名字(注释的作者)
    Myecplise Tomcat 启动很慢
    Java Enum 比较用 == 还是 eques
    Spring JDBC查询返回对象代码跟踪
    Apache启动失败(Windows 无法在本地计算机启动Apache2.2)
    SQLServer2008 统计表占用空间
    SET IDENTITY_INSERT ON/OFF 权限
    字母出现频率
    统计单词数
    查找最大元素
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13508519.html
Copyright © 2020-2023  润新知