美文网首页
147. Insertion Sort List

147. Insertion Sort List

作者: Leorio_c187 | 来源:发表于2017-06-15 09:33 被阅读0次

题目

Sort a linked list using insertion sort.

思路

这道题花费了最多的时间。

  1. 复习了array的插入排序,用两个循环实现,每次循环到下一个数,和之前的比较,往前不断挪动位置
  2. 运用在array的东西挪到linkedlist上就变得比较麻烦。 但基本思路和array操作一样
  3. 有一个优化,直接把tle变成通过,就是每次只当cur的值小于当前head值时,才把cur回移动到最开始

Python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    # Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def insertionSortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        #something really easy on array become really hard on Linked list!!!
        cur = dummy = ListNode(0) #The returning list, use it to iterate from start each time
        while head:
            if cur and cur.val > head.val: # Added a line to do the optmization
                cur = dummy # The "pre" pointer will help us find out the right position
            while cur.next and cur.next.val < head.val: #move the pre pointer to find the right place
                cur = cur.next
            
            cur.next, cur.next.next, head = head, cur.next, head.next
        return dummy.next

相关文章

  • 147. Insertion Sort List

    题目147. Insertion Sort List Sort a linked list using inser...

  • 147. Insertion Sort List

    题目要求: Sort a linked list using insertion sort.利用插入排序对一个链表...

  • 147. Insertion Sort List

    插入结点 但是 超时了。。 嗯 很蠢的做法 不超时的做法:

  • 147. Insertion Sort List

    思路 插入排序的思想,将未排序的与已知排好序的作比较,进行插入 创建一个链表来作为已知链表(rptr), 比较的是...

  • 147. Insertion Sort List

    题目 Sort a linked list using insertion sort. 思路 这道题花费了最多的时...

  • 147. Insertion Sort List

    Sort a linked list using insertion sort.使用插入排序法排链表。

  • 147. Insertion Sort List

    Sort a linked list using insertion sort.

  • 147. insertion sort list

    Sort a linked list using insertion sort. 这题是用插入排序排序一个链表。插...

  • 147. Insertion Sort List

    对链表进行插入排序。 插入排序的基本思想是,维护一个有序序列,初始时有序序列只有一个元素,每次将一个新的元素插入到...

  • 2018-11-10

    147.Insertion Sort List Sort a linked list using insertio...

网友评论

      本文标题:147. Insertion Sort List

      本文链接:https://www.haomeiwen.com/subject/pyryqxtx.html