题解 | #对链表进行插入排序#
对链表进行插入排序
https://www.nowcoder.com/practice/cc6c61215dfb446f8eccea3663e3d8db
using System; using System.Collections.Generic; /* public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } */ class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode insertionSortList(ListNode head) { // write code here ListNode lnRtn = new ListNode(0); while (head != null) { ListNode lnRtnD = lnRtn; ListNode lnFindPre = null; while (lnRtnD.next != null) { if (lnRtnD.next != null && lnRtnD.next.val > head.val) { lnFindPre = lnRtnD; break; } lnRtnD = lnRtnD.next; } if (lnFindPre != null) { ListNode lnTmp = head.next; ListNode lnFindN = lnFindPre.next; lnFindPre.next = head; head.next = lnFindN; head = lnTmp; } else { ListNode lnHN = head.next; lnRtnD.next = head; head.next = null; head = lnHN; } } return lnRtn.next; } }