Skip to content

Commit 2f36728

Browse files
committed
🐱(link): 147. 对链表进行插入排序
1 parent d2f91e8 commit 2f36728

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

docs/data-structure/linked_list/README.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,52 @@ class Solution:
475475
return False
476476
```
477477

478+
## 147. 对链表进行插入排序
479+
480+
[原题链接](https://leetcode-cn.com/problems/insertion-sort-list/)
481+
482+
### Tail 优化版
483+
484+
```python
485+
# Definition for singly-linked list.
486+
# class ListNode:
487+
# def __init__(self, x):
488+
# self.val = x
489+
# self.next = None
490+
491+
class Solution:
492+
def insertionSortList(self, head: ListNode) -> ListNode:
493+
if head is None or head.next is None:
494+
return head
495+
496+
# 固定头部
497+
new_head = ListNode(float("-inf"))
498+
499+
cur = head
500+
pre = new_head
501+
502+
# 加入尾部
503+
tail = new_head
504+
505+
while cur is not None:
506+
if tail.val < cur.val:
507+
tail.next = cur
508+
tail = cur
509+
cur = cur.next
510+
else:
511+
cur_next = cur.next
512+
# 此时:tail.next = cur,会产生循环,故断开
513+
tail.next = cur_next
514+
while pre.next is not None and pre.next.val < cur.val:
515+
pre = pre.next
516+
cur.next = pre.next
517+
pre.next = cur
518+
cur = cur_next
519+
pre = new_head
520+
521+
return new_head.next
522+
```
523+
478524
## 148. 排序链表
479525

480526
[原题链接](https://leetcode-cn.com/problems/sort-list/)

0 commit comments

Comments
 (0)