2018-11-10

147. Insertion Sort List

Sort a linked list using insertion sort.

A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.

With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list

Algorithm of Insertion Sort:

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.

At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.

It repeats until no input elements remain.

Example 1:

            Input:4->2->1->3

            Output:1->2->3->4

Example 2:

            Input:-1->5->3->4->0

            Output:-1->0->3->4->5

分析:这道题目主要是要求我们对链表进行插入排序,题意要求非常简单,我采用的是数组版插入排序思路,只是在插入的时候,由于链表与数组的差异,我是从链表投开始进行插入判断,再解决本题的时候,发生了超时的状况,思考久久,意外在代码中去掉了一个else(注释的地方)后竟然通过了,从本题中我学习到其实else也是会让程序变慢的(虽然以前也知道,实际第一次这么尝试),加深了对编程这一行的认识!!!

但是不足之处是效率较低,别人都是先获取数据进行排序,然后构建新的链表,没的说,自己太菜了,以后还是要多多努力!

# Definition for singly-linked list.

# class ListNode:

#    def __init__(self, x):

#        self.val = x

#        self.next = None

class Solution:

    def insertionSortList(self, head):

        """

        :type head: ListNode

        :rtype: ListNode

        """

        if head==None or head.next==None:

            return head

        curhead = head

        cur = head.next

        tempNode = head

        while cur!=None:

            if cur.val < tempNode.val:

                curhead = head

                while curhead!= cur:

                    if curhead.val > cur.val:

                        curhead.val,cur.val = cur.val,curhead.val

                    else      #就是这个else导致超时

                    curhead = curhead.next

            tempNode = cur

            cur = cur.next

        return head

你可能感兴趣的:(2018-11-10)