题目
基础题目:
21. 合并两个有序链表
876. 链表的中间结点
法1:归并排序,自上而下
基本好法,必须掌握!
时间复杂度:O(nlgn)
Python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
slow, fast = head, head
pre = None # slow的前序节点
while fast and fast.next:
pre = slow
slow = slow.next
fast = fast.next.next
pre.next = None
l1 = self.sortList(head)
l2 = self.sortList(slow)
return self.merge(l1, l2)
def merge(self, l1, l2):
dummy = ListNode(-1)
cur, cur1, cur2 = dummy, l1, l2
while cur1 and cur2:
if cur1.val <= cur2.val:
cur.next = cur1
cur1 = cur1.next
else:
cur.next = cur2
cur2 = cur2.next
cur = cur.next
cur.next = cur1 if cur1 else cur2
return dummy.next
Java
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) {
return head;
合并有序链表的多种算法实现

文章介绍了四种方法来合并两个已排序的链表,包括归并排序的自上而下和自底向上策略,优先队列以及修改节点值的方法。
最低0.47元/天 解锁文章
354

被折叠的 条评论
为什么被折叠?



