题解 | #单链表的排序#

单链表的排序

https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

阿巴阿巴阿巴阿巴阿巴阿巴阿巴
抛开事实不谈,这应该是最简单的吧,只是面试的时候考官可能会让你滚
package main
import . "nc_tools"
import "sort"
/*
 * type ListNode struct{
 *   Val int
 *   Next *ListNode
 * }
 */

/**
 * 
 * @param head ListNode类 the head node
 * @return ListNode类
*/
func sortInList(head *ListNode) *ListNode {
    // write code here
    res := []*ListNode{}
    for head != nil {
        res = append(res, head)
        v := head.Next
        head.Next = nil
        head = v
    }
    sort.Slice(res, func(i, j int) bool {
        return res[i].Val < res[j].Val
    })
    dummy := &ListNode{}
    node := dummy
    for i := 0; i < len(res); i++ {
        node.Next = res[i]
        node = node.Next
    }
    return dummy.Next
}




全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
04-08 00:50
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务