题解 | #单链表的排序#

单链表的排序

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
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-25 17:26
点赞 评论 收藏
分享
06-26 22:20
门头沟学院 Java
码农索隆:让你把简历发给她,她说一些套话,然后让你加一个人,说这个人给你改简历,然后开始卖课
我的求职精神状态
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务