C#-sort()利用委托自定义排序

文章速览

坚持记录实属不易,希望友善多金的码友能够随手点一个赞。
共同创建氛围更加良好的开发者社区!
谢谢~

前言:

使用委托自定义Sort()方法,实现排序

例子:演示的是对链表的排序

力扣算法中等题:147、对链表进行插入排序的非标准解法

核心代码:

委托自定义排序

csharp 复制代码
			//委托自定义排序
            list.Sort(
                (x, y) =>
                {
                    if(x.val > y.val)
                    {
                        return 1;
                    }
                    else if(x.val < y.val)
                    {
                        return -1;
                    }
                    return 0;
                }                
                );

完整示例:对链表实现自定义排序

1、链表类

csharp 复制代码
//Definition for singly-linked list.
public class ListNode {
     public int val;
     public ListNode next;
    public ListNode(int val=0, ListNode next=null) {
        this.val = val;
        this.next = next;
    }
 }

2、解决方案:

以val的值为标准,对链表进行排序;

返回链表的头节点

csharp 复制代码
public class Solution {
    public ListNode SortList(ListNode head) {
            if(head.next == null)
            {
                return head;
            }
            ListNode currrent = head;

            List<ListNode> list = new List<ListNode>();

            while(currrent != null)
            {
                list.Add(currrent);
                currrent = currrent.next;
            }
			//委托自定义排序
            list.Sort(
                (x, y) =>
                {
                    if(x.val > y.val)
                    {
                        return 1;
                    }
                    else if(x.val < y.val)
                    {
                        return -1;
                    }
                    return 0;
                }                
                );

            for( int i = 0; i < list.Count - 1; i++)
            {
                list[i].next = list[i + 1];
            }
            list[list.Count - 1].next = null;

            return list[0];
        }
}
相关推荐
Blossom.1182 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算
da-peng-song2 小时前
ArcGIS Desktop使用入门(二)常用工具条——数据框工具(旋转视图)
开发语言·javascript·arcgis
galaxy_strive2 小时前
qtc++ qdebug日志生成
开发语言·c++·qt
TNTLWT2 小时前
Qt功能区:简介与安装
开发语言·qt
CoderIsArt3 小时前
参数系统的基类Parameter抽象类
c#
等等5433 小时前
Java EE初阶——wait 和 notify
java·开发语言
低代码布道师4 小时前
第五部分:第一节 - Node.js 简介与环境:让 JavaScript 走进厨房
开发语言·javascript·node.js
盛夏绽放4 小时前
Python字符串常用方法详解
开发语言·python·c#
好吃的肘子5 小时前
Elasticsearch架构原理
开发语言·算法·elasticsearch·架构·jenkins
nlog3n5 小时前
Go语言交替打印问题及多种实现方法
开发语言·算法·golang