商城网站互动性,需要企业网站开发,百度推广排名怎么做的,个人服务器搭建违法文章速览 前言#xff1a;核心代码#xff1a;完整示例#xff1a;对链表实现自定义排序1、链表类2、解决方案#xff1a; 坚持记录实属不易#xff0c;希望友善多金的码友能够随手点一个赞。 共同创建氛围更加良好的开发者社区#xff01; 谢谢~
前言#xff1a;
使用… 文章速览 前言核心代码完整示例对链表实现自定义排序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 val0, ListNode nextnull) {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;ListListNode list new ListListNode();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];}
}