Insertion Sort List
Sort a linked list using insertion sort.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode insertionSortList(ListNode head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(head == null) return null; ListNode curNode = null; ListNode preNode=null; ListNode nextNode=null; ListNode node = null; curNode = head.next; head.next = null; while(curNode!=null)//当前要插入的节点 { node = curNode.next;//保存下一个节点 if(curNode.val < head.val)//比头结点还小,则成为新的头结点 { curNode.next = head; head = curNode; } else { preNode = head; nextNode = head.next; while(nextNode!=null && nextNode.val<curNode.val)//找到合适位置 { preNode = nextNode; nextNode = nextNode.next; } curNode.next = preNode.next; preNode.next = curNode; } curNode = node; } return head;//返回新的头结点 } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步