原题网址:https://leetcode.com/problems/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; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode current = head.next;
head.next = null;
while (current != null) {
ListNode next = current.next;
if (current.val <= head.val) {
current.next = head;
head = current;
} else {
ListNode insert = head;
while (insert.next != null && current.val > insert.next.val) {
insert = insert.next;
}
if (insert.next == null) {
current.next = null;
insert.next = current;
} else {
current.next = insert.next;
insert.next = current;
}
}
current = next;
}
return head;
}
}
优化:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode insertionSortList(ListNode head) {
/*
下面这个是网上找来的
*/
ListNode dummy = new ListNode(0);
// 这个dummy的作用是,把head开头的链表一个个的插入到dummy开头的链表里
// 所以这里不需要dummy.next = head;
while (head != null) {
ListNode node = dummy;
while (node.next != null && node.next.val < head.val) {
node = node.next;
}
ListNode temp = head.next;
head.next = node.next;
node.next = head;
head = temp;
}
return dummy.next;
}
}

本文介绍了一种使用插入排序算法对链表进行排序的方法,并提供了两种实现方式。第一种通过直接在原始链表中进行元素的插入操作实现排序;第二种则是创建一个虚拟头节点,将原始链表中的元素逐一插入到新链表中完成排序。
373

被折叠的 条评论
为什么被折叠?



