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];
        }
}
相关推荐
zh_xuan1 小时前
kotlin lazy委托异常时执行流程
开发语言·kotlin
阿猿收手吧!2 小时前
【C++】string_view:高效字符串处理指南
开发语言·c++
玄同7652 小时前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
Yorlen_Zhang2 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
lxl13072 小时前
C++算法(1)双指针
开发语言·c++
不绝1913 小时前
C#进阶:预处理指令/反射,Gettype,Typeof/关键类
开发语言·c#
无小道3 小时前
Qt-qrc机制简单介绍
开发语言·qt
zhooyu3 小时前
C++和OpenGL手搓3D游戏编程(20160207进展和效果)
开发语言·c++·游戏·3d·opengl
HAPPY酷3 小时前
C++ 和 Python 的“容器”对决:从万金油到核武器
开发语言·c++·python
大鹏说大话3 小时前
告别 MSBuild 脚本混乱:用 C# 和 Nuke 构建清晰、可维护的现代化构建系统
开发语言·c#