题解 | #单链表的排序#

单链表的排序

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

using System;
using System.Collections.Generic;

/*
public class ListNode
{
    public int val;
    public ListNode next;

    public ListNode (int x)
    {
        val = x;
    }
}
*/

class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList(ListNode head) {
        // write code here
        List<int> listN = GetList(head);
        if (listN == null || listN.Count == 0)
            return null;
        listN.Sort();
        ListNode ln = new ListNode(listN[0]);
        ListNode lnRtn = ln;
        for (int i = 1; i < listN.Count; i++) {
            var tmp = ln.next;
            ListNode listNode = new ListNode(listN[i]);
            ln.next = listNode;
            listNode.next = tmp;
            ln = listNode;
        }
        return lnRtn;
    }

    public List<int> GetList(ListNode head) {
        // write code here
        if (head == null)
            return null;
        List<int> listN = new List<int>();
        while (head != null) {
            listN.Add(head.val);
            head = head.next;
        }
        return listN;
    }
}

全部评论

相关推荐

不要停下啊:大二打开牛客,你有机会开卷了,卷起来,去找课程学习,在牛客上看看大家面试笔试都需要会什么,岗位有什么需求就去学什么,努力的人就一定会有收获,这句话从来都经得起考验,像我现在大三了啥也不会,被迫强行考研,炼狱难度开局,啥也不会,找工作没希望了,考研有丝丝机会
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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