版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ccnuacmhdu/article/details/85227040
时间限制:1秒 空间限制:32768K 热度指数:32968
本题知识点: 排序 leetcode
算法知识视频讲解
题目描述
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) {
//果真是插入排序的思想,每次找到插入点,把节点插入
if(head == null || head.next == null){
return head;
}
ListNode v = new ListNode(-1);//将以v为头节点,构造成经过插入排序形成的有序链表
ListNode tmp = null;
while(head != null){
tmp = v;
//每次从前向后遍历已经排序的链表,找到插入位置
while(tmp.next != null && head.val > tmp.next.val){
tmp = tmp.next;
}
//把当前节点head插入到找到的位置
ListNode headNext = head.next;
head.next = tmp.next;
tmp.next = head;
head = headNext;//head后移一步
}
return v.next;
}
}