【LeetCode】147.对链表进行插入排序

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time: 2019/3/26
# @Author: xfLi
# The file...

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def insertionSortList(head):
    if not head:
        return head
    h = ListNode(0)
    h.next = head
    pre = h
    cur = head
    while cur:
        lat = cur.next
        if lat and lat.val < cur.val:  # 只有cur.next比cur小的时候我们才寻找插入点
            while pre.next and pre.next.val < lat.val:
                pre = pre.next
            tmp = pre.next
            pre.next = lat
            cur.next = lat.next
            lat.next = tmp
            pre = h
        else:
            cur = lat
    return h.next


猜你喜欢

转载自blog.csdn.net/qq_30159015/article/details/88831492