题解 | #单链表的排序#

单链表的排序

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

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务