Leetcode 147. Insertion Sort List
Description: Sort a linked list using insertion sort.
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.
Link: https://leetcode.com/problems/insertion-sort-list/
Examples:
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
思路: 依照插入排序的方法,两层循环,外层遍历没有排序的节点,内层寻找该节点的位置,即从头遍历已排序的部分,直到值大于当前节点的值,连接到其前面的节点pre上。
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def insertionSortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head: return head if not head.next: return head p = head.next rh = ListNode(0) rh.next = ListNode(head.val) while p: r = rh.next pre = rh while r and p.val >= r.val: pre = r r = r.next s = p.next pre.next = p p.next = r p = s return rh.next
日期: 2020-11-28 加油呀!