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];
        }
}
相关推荐
唐人街都是苦瓜脸1 小时前
Java RPC 框架是什么
java·开发语言·rpc
黑不溜秋的1 小时前
Ubuntu24.04 编译 Qt 源码
开发语言·qt
ALex_zry1 小时前
C++17模板编程与if constexpr深度解析
开发语言·c++·性能优化
AugustShuai1 小时前
API-标准controller接口
开发语言·json·设计规范·post·标准接口
幻想趾于现实2 小时前
C# Winform 入门(15)之制作二维码和拼接(QR)
开发语言·c#·winform
wniuniu_2 小时前
Pow工作量证明是啥
开发语言·区块链·php
多云的夏天2 小时前
C++-FFmpeg-(5)-1-ffmpeg原理-ffmpeg编码接口-AVFrame-AVPacket-最简单demo
java·开发语言
leluckys2 小时前
swift-11-init、deinit、可选链、协议、元类型
开发语言·ios·swift
njsgcs2 小时前
vscode swift hello world
开发语言·ios·swift
霸道流氓气质2 小时前
Winform入门进阶企业级开发示例:http接口数据清洗转换、断线续传、mqtt数据传输实例详解(附代码资源下载)
http·c#·winform