题目描述
- 标签(题目类型):链表、排序
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目在范围 [0, 5 * 104] 内
-105 <= Node.val <= 105
进阶:你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
原题:148. 排序链表
思路及实现
方式一:归并排序(续)
C语言版本(续)
// 释放链表内存
void freeList(struct ListNode* head) {
struct ListNode *cur = head;
while (cur != NULL) {
struct ListNode *temp = cur;
cur = cur->next;
free(temp);
}
}
struct ListNode* sortList(struct ListNode* head) {
// ... 省略之前的代码 ...
// 释放dummy节点内存
free(dummy);
return result;
}
说明:
freeList
函数用于释放链表占用的内存。- 在
sortList
函数最后,释放了dummy
节点占用的内存,并返回排序后的链表头节点result
。
Python3版本
# 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: ListNode) -> ListNode:
if not head or not head.next:
return head
# 使用快慢指针找到链表中间节点
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
# 分割链表
mid = slow.next
slow.next = None
# 递归对左右两部分链表排序
left = self.sortList(head)
right = self.sortList(mid)
# 合并两个已排序链表
return self.merge(left, right)
def merge(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
cur = dummy
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
# 处理剩余节点
cur.next = l1 if l1 is not None else l2
return dummy.next
说明:
- Python版本的实现与Java版本类似,但语法有所不同。
- Python中的链表节点定义使用了类,并且链表操作更为简洁。
Golang版本
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func sortList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
slow, fast