链表排序 python 力扣148
2022/1/14 9:03:33
本文主要是介绍链表排序 python 力扣148,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
力扣148 https://leetcode-cn.com/problems/sort-list/
归并排序单向链表 完整解法
# from utils import ListNode, LinkList from typing import List class ListNode(object): def __init__(self, val=None, next=None): self.val = val self.next = next def __repr__(self): res = '' p = self.next res = '' + str(self.val) + '-->' while p: tmp = str(p.val) tmp = tmp + '-->' if p.next else tmp res += tmp p = p.next return res def LinkList(lst: List) -> ListNode: if not lst: return None head = ListNode(lst[0]) p = head for i in range(1, len(lst)): p.next = ListNode(lst[i]) p = p.next return head def sortList(head: ListNode) -> ListNode: if not head or not head.next: return head slow, fast = head, head.next # find the mid and cut the LinkList while fast and fast.next: slow, fast = slow.next, fast.next.next mid, slow.next = slow.next, None left, right = sortList(head), sortList(mid) # merge two sorted LinkList dummy = ListNode(0) p = dummy while left and right: if left.val < right.val: p.next, left = left, left.next else: p.next, right = right, right.next p = p.next p.next = left if left else right return dummy.next if __name__ == "__main__": ins = LinkList([1, 6, 3, 9, 7, 5]) print(ins) outs = sortList(ins) print(outs)
这篇关于链表排序 python 力扣148的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-03用FastAPI掌握Python异步IO:轻松实现高并发网络请求处理
- 2025-01-02封装学习:Python面向对象编程基础教程
- 2024-12-28Python编程基础教程
- 2024-12-27Python编程入门指南
- 2024-12-27Python编程基础
- 2024-12-27Python编程基础教程
- 2024-12-27Python编程基础指南
- 2024-12-24Python编程入门指南
- 2024-12-24Python编程基础入门
- 2024-12-24Python编程基础:变量与数据类型