原题
https://leetcode.cn/problems/sort-list/description/
思路
转为列表后排序
复杂度
时间:O(n * log(n))
空间:O(n)
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:
return None
l = []
while head:
l.append(head.val)
head = head.next
l.sort()
dummy = cur = ListNode(-1)
for val in l:
cur.next = ListNode(val)
cur = cur.next
return dummy.next
Go代码
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func sortList(head *ListNode) *ListNode {
if head == nil {
return head
}
l := []int{}
for head != nil {
l = append(l, head.Val)
head = head.Next
}
sort.Ints(l)
dummy := &ListNode{}
cur := dummy
for _, val := range l {
cur.Next = &ListNode{Val: val}
cur = cur.Next
}
return dummy.Next
}
1283

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



