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];
        }
}
相关推荐
m0_6873998412 分钟前
写一个Ununtu C++ 程序,调用ffmpeg API, 来判断一个数字电影的视频文件mxf 是不是Jpeg2000?
开发语言·c++·ffmpeg
爱上语文22 分钟前
Redis基础(5):Redis的Java客户端
java·开发语言·数据库·redis·后端
A~taoker28 分钟前
taoker的项目维护(ng服务器)
java·开发语言
萧曵 丶31 分钟前
Rust 中的返回类型
开发语言·后端·rust
hi星尘1 小时前
深度解析:Java内部类与外部类的交互机制
java·开发语言·交互
看到我,请让我去学习1 小时前
Qt编程-qml操作(js,c++,canvas)
开发语言·qt
橘子编程1 小时前
Python-Word文档、PPT、PDF以及Pillow处理图像详解
开发语言·python
Ronin3052 小时前
【C++】类型转换
开发语言·c++
mrbone112 小时前
Git-git worktree的使用
开发语言·c++·git·cmake·worktree·gitab
浪裡遊2 小时前
Sass详解:功能特性、常用方法与最佳实践
开发语言·前端·javascript·css·vue.js·rust·sass