题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/** * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int = 0, _ next: ListNode? = nil) { * self.val = val * self.next = next * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 the head node * @return ListNode类 */ func sortInList ( _ head: ListNode?) -> ListNode? { // write code here if head == nil || head?.next == nil { return head } var map: [Int: Int] = [:] var cur = head while cur != nil { map[cur!.val, default: 0] += 1 cur = cur!.next } var arr = map.keys.sorted(by:{$0<$1}) var res = ListNode() var node = res for i in arr { let t = map[i]! for _ in 0..<t { let n = ListNode() n.val = i node.next = n if let next = node.next { node = next } } } return res.next } }