leetcode-147- sorted linked list insertion

Subject description:

method one:

# Definition List for Singly-linked. 
# Class ListNode: 
#      DEF the __init __ (Self, X): 
#          self.val = X 
#          self.next = None 

class Solution:
     DEF insertionSortList (Self, head: ListNode) -> ListNode:
         IF  not head or  not head.next:
             return head 
        
        dummy = ListNode (-1 ) 
        dummy.next = head 
        pre = head # pre always pointing to sort the last node in the list of good 
        CUR = head.next #cur always pointing to the first node in the list unsorted 
        the while cur: 
            tail = cur.next 
            pre.next = tail   # to this node out cur 
            
            P = dummy
             the while p.next and p.next.val <Cur.Val: # locate the insert positions 
                p = p.next 
                
            cur.next = p.next # the cur inserted between the p and p.next 
            p.next = cur 
            cur = tail 
            
            IF p == pre: # If you have just inserted into the sorted the end of the list of 
                pre = pre.next #Then update pre 
        return dummy.next

another:

class Solution (Object):
     DEF insertionSortList (Self, head):
         "" " 
        : type head: ListNode 
        : rtype: ListNode 
        " "" 
        dummy = ListNode (a float ( ' -INF ' ))
         the while head: 
            P = dummy
             # lists plug find the last row is smaller than the head of a node pointing to head 
            the while p.next and p.next.val < head.val: 
                P = p.next 
            Q = head # Q head head replacement step forward 
            head = head.next
            p.next, q.next = q, p.next
        return dummy.next

cheat:

class Solution:
    def insertionSortList(self, head: ListNode) -> ListNode:
        #naive
        nodeList = []
        while(head):
            nodeList.append(head)
            head = head.next
        nodeList.sort(key=lambda x:x.val)
        dummy = ListNode(0)
        pre = dummy
        for node in nodeList:
            pre.next = node
            pre = node
        pre.next = None
        return dummy.next

 

Guess you like

Origin www.cnblogs.com/oldby/p/11201540.html