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];
        }
}
相关推荐
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫1 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下2 天前
最终的信号类
开发语言·c++·算法
echoarts2 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix2 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题2 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说2 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔2 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机