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

文章速览

  • 前言:
  • 核心代码:
  • 完整示例:对链表实现自定义排序
    • 1、链表类
    • 2、解决方案:

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

前言:

使用委托自定义Sort()方法,实现排序
例子:演示的是对链表的排序
(力扣算法中等题:147、对链表进行插入排序的非标准解法)

核心代码:

委托自定义排序

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

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

1、链表类

//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的值为标准,对链表进行排序;
返回链表的头节点

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];}
}