148. 排序链表 - 力扣(LeetCode)

暴力算法

python 复制代码
# encoding = utf-8
# 开发者:Alen
# 开发时间: 10:51 
# "Stay hungry,stay foolish."

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution(object):
    def sortList(self, head):
        """
        :type head: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        # Step 1: 提取所有值
        cur = head
        values = []
        while cur:
            values.append(cur.val)
            cur = cur.next

        # Step 2: 排序(注意:题目是排序链表,不是反转!)
        values.sort()  # 升序排序

        # Step 3: 重建链表
        dummy = ListNode(0)  # 哑节点,方便操作
        current = dummy
        for val in values:
            current.next = ListNode(val)
            current = current.next

        return dummy.next

归并算法

大佬图示:

代码:

python 复制代码
# encoding = utf-8
# 开发者:Alen
# 开发时间: 10:51 
# "Stay hungry,stay foolish."

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution(object):
    def sortList(self, head):
        """
        :type head: Optional[ListNode]
        :rtype: Optional[ListNode]
        """
        if not head or not head.next:
            return head

        left = head
        right = self.getMid(head)
        tmp = right.next
        right.next = None
        right = tmp

        left = self.sortList(left)
        right = self.sortList(right)
        return self.merge(left, right)

    def getMid(self, head):
        fast = head.next
        slow = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        return slow

    def merge(self, list1, list2):
        tail = dummy = ListNode()
        while list1 and list2:
            if list1.val < list2.val:
                tail.next = list1
                list1 = list1.next
            else:
                tail.next = list2
                list2 = list2.next
            tail = tail.next

        # 其中一个链为None,另一个可能不是None
        if list1:
            tail.next = list1

        if list2:
            tail.next = list2

        return dummy.next

结果

解题步骤:

相关推荐
琢磨先生David5 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245035 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll5 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐5 天前
leetcode-最小栈
java·算法·leetcode
岛雨QA5 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc5 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg15 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA5 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX5 天前
020-C++之unordered容器
数据结构·c++