zoukankan      html  css  js  c++  java
  • leetcode147 Insertion Sort List

     1 """
     2 链表插入排序
     3 """
     4 """
     5 难点在于设计链表,插入排序时如何找到插入位置,并恢复好下一个遍历结点的位置
     6 所以需要两个while循环,第一个是整体遍历,第二个是找插入位置
     7 """
     8 class ListNode:
     9     def __init__(self, x):
    10         self.val = x
    11         self.next = None
    12 
    13 class Solution:
    14     def insertionSortList(self, head):
    15         if not head or not head.next:
    16             return head
    17         first = ListNode(0)
    18         first.next = head  # 本题用三个指针来操作
    19         pre = head
    20         cur = head.next
    21         while cur:
    22             if pre.val < cur.val:  # 如果有序,向后遍历
    23                 pre = cur
    24                 cur = cur.next
    25             else:
    26                 pre.next = cur.next  # 保存下一个要遍历的位置
    27                 insert = first  # 用指针在前面找插入位置
    28                 while insert.next and insert.next.val < cur.val:  # 找到插入位置
    29                     insert = insert.next
    30                 cur.next = insert.next  # 插入结点
    31                 insert.next = cur
    32                 cur = pre.next  # 指针归位
    33         return first.next
  • 相关阅读:
    Redux API之applyMiddleware
    Redux API之combineReducers
    Redux API之creatStore
    Redux API之Store
    React-Redux之API
    ES6之6种遍历对象属性的方法
    React库protypes属性
    js立即执行函数
    Collection与Map总结
    02-再探MySQL数据库
  • 原文地址:https://www.cnblogs.com/yawenw/p/12324155.html
Copyright © 2011-2022 走看看