题目描述:
使用List放入ListNode,然后依据插入排序进行,这个时间少,空间复杂度低
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
if(head == null){
return head;
}
// 链表头部
ListNode pre = new ListNode(-1);
List<ListNode> listnode = new ArrayList<>();
pre.next = head;
listnode.add(pre);
listnode.add(head);
ListNode tem = head.next;
while (tem != null) {
ListNode getListNode = tem.next;
int size = listnode.size() - 1;
while (size >= 1) {
if(listnode.get(size).val <= tem.val){
break;
}
size --;
}
listnode.add(size + 1,tem);
tem = getListNode;
}
for (int i = 0; i < listnode.size() - 1; i++) {
listnode.get(i).next = listnode.get(i + 1);
}
listnode.get(listnode.size() - 1).next = null;
return listnode.get(0).next;
}
}
如果复杂度不允许那么需要考虑的就是把前一个节点得到,然后遍历
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode pre = new ListNode(-1);
pre.next = head;
while (head != null && head.next != null) {
if (head.val <= head.next.val) {
head = head.next;
continue;
}
ListNode tem = pre;
while (tem.next.val < head.next.val) {
tem = tem.next;
}
ListNode tempre = tem.next;
ListNode temnext = head.next.next;
tem.next = head.next;
head.next.next = tempre;
head.next = temnext;
}
return pre.next;
}
}